javajava-8java-streamincompatibletypeerror

How do I stream objects of incompatible types into a list?


My question is: Given a list of persons, return all students.

Here are my classes:

Person class

public class Person {
}

Student class

public class Student extends Person {
}

Method

public static List<Student> findStudents(List<Person> list) {


    return list.stream()
            .filter(person -> person instanceof Student)
            .collect(Collectors.toList());
}

I'm getting a compile error: incompatible types: inference variable T has incompatible bounds

How do I return all the students from the list using stream without getting this error.


Solution

  • return list.stream()
               .filter(Student.class::isInstance)
               .map(Student.class::cast)
               .collect(Collectors.toList());
    

    It should be a cast there, otherwise, it's still a Stream<Person>. The instanceof check doesn't perform any cast.

    Student.class::isInstance and Student.class::cast is just a preference of mine, you could go with p -> p instanceof Student and p -> (Student)p respectively.