java中Stream Collectors.toList()中的不兼容类型

use*_*895 1 java graph

我正在实现图形表示。

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)

但是我有一个错误

在此处输入图片说明

有没有办法为此使用流?

ern*_*t_k 6

由于您的值已经输入为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)