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

我的问题是:给定一个人员名单,返回所有学生。


这是我的课程:


人物类


public class Person {

}

学生班


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


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


忽然笑
浏览 186回答 3
3回答

回首忆惘然

return&nbsp;list.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(Student.class::isInstance) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.map(Student.class::cast) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toList());它应该在那里进行强制转换,否则,它仍然是一个Stream<Person>.&nbsp;该instanceof检查不执行任何强制转换。Student.class::isInstance和Student.class::cast只是我的偏好,您可以分别选择p -> p instanceof Student和p -> (Student)p。

慕盖茨4494581

你需要一个演员:public static List<Student> findStudents(List<Person> list)&nbsp;{&nbsp; &nbsp; return list.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.filter(person -> person instanceof Student)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(person -> (Student) person)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toList());}

拉丁的传说

另一种选择。public static List<Student> findStudents(List<Person> list)&nbsp;{&nbsp; &nbsp; return list.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(s -> Student.class.equals(s.getClass()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(Student.class::cast)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java