亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將不兼容類型的對象流式傳輸到列表中?

如何將不兼容類型的對象流式傳輸到列表中?

忽然笑 2023-08-23 15:00:33
我的問題是:給定一個人員名單,返回所有學生。這是我的課程:人物類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如何使用流返回列表中的所有學生而不會出現此錯誤。
查看完整描述

3 回答

?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

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。


查看完整回答
反對 回復 2023-08-23
?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

你需要一個演員:


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

{

    return list.stream()

               .filter(person -> person instanceof Student) 

               .map(person -> (Student) person)

               .collect(Collectors.toList());

}


查看完整回答
反對 回復 2023-08-23
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

另一種選擇。


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

}


查看完整回答
反對 回復 2023-08-23
  • 3 回答
  • 0 關注
  • 225 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號