我正在实现图形表示。
Map<V, List<E<V>>> g = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
但是我想用
List<E<V>> getAllEdges() {
return g.values().stream().collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
但是我有一个错误
有没有办法为此使用流?
由于您的值已经输入为List<E<V>,.collect(Collectors.toList())因此如果您要构建一个,则使用为宜List<List<E<V>>。
要解决此问题,请使用flatMap:展平2D列表:
List<E<V>> getAllEdges() {
return g.values().stream().flatMap(List::stream).collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |