[英]Incompatible types in stream Collectors.toList() in java
我正在實現圖形表示。
Map<V, List<E<V>>> g = new HashMap<>();
Graph類的方法之一是
List<E<V>> getAllEdges() {
List<E<V>> allEdges = new ArrayList<>();
for(Map.Entry<V, List<E<V>>> entry: g.entrySet()) {
allEdges.addAll(entry.getValue());
}
return allEdges;
}
但是我想用
List<E<V>> getAllEdges() {
return g.values().stream().collect(Collectors.toList());
}
但是我有一個錯誤
有沒有辦法為此使用流?
由於您的值已經輸入為List<E<V>
, .collect(Collectors.toList())
如果要構建List<List<E<V>>
,則使用.collect(Collectors.toList())
是合適的。
要解決此問題,請使用flatMap
展平2D列表:
List<E<V>> getAllEdges() {
return g.values().stream().flatMap(List::stream).collect(Collectors.toList());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.