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

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

“錯誤:不兼容的類型:推理變量 R 具有不兼容的邊界”當 flatMap 單行中的流

“錯誤:不兼容的類型:推理變量 R 具有不兼容的邊界”當 flatMap 單行中的流

揚帆大魚 2021-12-10 14:43:23
我有一個自定義類Custom。public class Custom {  private Long id;  List<Long> ids;  // getters and setters}現在我有List<Custom>對象了。我想轉換List<Custom>成List<Long>. 我已經編寫了如下代碼,它工作正常。    List<Custom> customs = Collections.emptyList();    Stream<Long> streamL = customs.stream().flatMap(x -> x.getIds().stream());    List<Long> customIds2 = streamL.collect(Collectors.toList());    Set<Long> customIds3 = streamL.collect(Collectors.toSet());現在我將 line2 和 line3 組合成單行,如下所示。    List<Long> customIds = customs.stream().flatMap(x -> x.getIds().stream()).collect(Collectors.toSet());現在,此代碼未編譯,并且出現以下錯誤 -    error: incompatible types: inference variable R has incompatible bounds            List<Long> customIds = customs.stream().flatMap(x -> x.getIds().stream()).collect(Collectors.toSet());                                                                                            ^        equality constraints: Set<Long>        upper bounds: List<Long>,Object    where R,A,T are type-variables:        R extends Object declared in method <R,A>collect(Collector<? super T,A,R>)        A extends Object declared in method <R,A>collect(Collector<? super T,A,R>)        T extends Object declared in interface Stream我怎樣才能轉換List<Custom>成Set<Long>或List<Long>正確
查看完整描述

2 回答

?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

你可以這樣做:


List<Custom> customs = Collections.emptyList();

Set<Long> customIdSet = customs.stream()

                               .flatMap(x -> x.getIds().stream())

                               .collect(Collectors.toSet()); // toSet and not toList

您收到編譯器錯誤的原因是您使用了一個不正確的方法Collector,它返回一個 List 而不是 Set,后者是您將它分配給Set<Long>類型變量時的預期返回類型。


查看完整回答
反對 回復 2021-12-10
?
慕森王

TA貢獻1777條經驗 獲得超3個贊

這應該可以解決問題:

Set<Long> collectSet = customs.stream()
                           .flatMap(x -> x.getIds().stream())
                           .collect(Collectors.toSet());

您正在嘗試將 a 轉換Set為 a List,這是不可能的。



查看完整回答
反對 回復 2021-12-10
  • 2 回答
  • 0 關注
  • 895 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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