How do I stream objects of incompatible types into a list?
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.
You need a cast:
public static List<Student> findStudents(List<Person> list)
{
return list.stream()
.filter(person -> person instanceof Student)
.map(person -> (Student) person)
.collect(Collectors.toList());
}
Another alternative.
public static List<Student> findStudents(List<Person> list)
{
return list.stream()
.filter(s -> Student.class.equals(s.getClass()))
.map(Student.class::cast)
.collect(Collectors.toList());
}