javalistgenericsjava-streamunbounded-wildcard

Unable to assign the result returned by the Method that receives a generic List and returns a List<?>


I'm trying to filter a List of objects that implements an interface. And I'm trying to create a generic method for all the classes.

Something like:

interface SomeInterface {
    String getFlag();
}


class SomeObject implements SomeInterface {
    public String getFlag() {
        return "X";
    }
}


List<SomeObject> someObjectList = new ArrayList<>();

// Compilation error here
List<SomeObject> filterList = filterGenericList(someObjectList, "X");


private List<?> filterGenericList(List<? extends SomeInterface> objects, String flag) {
        return objects.stream()
                .filter(it -> it.getFlag().equals(flag))
                .collect(Collectors.toList());
}

How do I run away from the compilation Error?

 Incompatible types. 
 Found: 'java.util.List<capture<?>>', 
 Required: 'java.util.List<SomeObject>'

Solution

  • When you return List<?> that means the method returns a list of some unknown type. Java doesn't know that it's the same type of list as the input list. To signal that, create a generic type T and have both the input and output lists be List<T>.

    private <T extends SomeInterface> List<T> filterGenericList(List<T> objects, String flag) {
        return objects.stream()
            .filter(it -> it.getFlag().equals(flag))
            .collect(Collectors.toList());
    }