如何将不兼容类型的对象流式传输到列表中?

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

我的问题是:给定一个人员列表,return 所有学生。

这是我的 classes:

人class

public class Person {
}

学生class

public class Student extends Person {
}

方法

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


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

我遇到编译错误:incompatible types: inference variable T has incompatible bounds

如何return 列表中的所有学生使用流而不出现此错误。

你需要演员表:

public static List<Student> findStudents(List<Person> list) 
{
    return list.stream()
               .filter(person -> person instanceof Student) 
               .map(person -> (Student) person)
               .collect(Collectors.toList());
}
return list.stream()
           .filter(Student.class::isInstance)
           .map(Student.class::cast)
           .collect(Collectors.toList());

那里应该是演员表,否则还是Stream<Person>instanceof 检查不执行任何转换。

Student.class::isInstanceStudent.class::cast只是我的喜好,你可以分别选择p -> p instanceof Studentp -> (Student)p

另一种选择。

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());
}