我有一個自定義類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>類型變量時的預期返回類型。

慕森王
TA貢獻1777條經驗 獲得超3個贊
這應該可以解決問題:
Set<Long> collectSet = customs.stream() .flatMap(x -> x.getIds().stream()) .collect(Collectors.toSet());
您正在嘗試將 a 轉換Set
為 a List
,這是不可能的。
添加回答
舉報
0/150
提交
取消