user2761895
user2761895

Reputation: 1541

Incompatible types in stream Collectors.toList() in java

I'm implementing graph representation.

Map<V, List<E<V>>> g = new HashMap<>();

one of methods in Graph class is

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;
}

But I'd like to make it shorter line using

List<E<V>> getAllEdges() {
    return  g.values().stream().collect(Collectors.toList());
}

but I have an error such that

enter image description here

Is there a way to use stream for this?

Upvotes: 1

Views: 120

Answers (1)

ernest_k
ernest_k

Reputation: 45309

Since your values are already typed as List<E<V>, using .collect(Collectors.toList()) is appropriate if you want to build a List<List<E<V>>.

To fix it, flatten the 2D list using flatMap:

List<E<V>> getAllEdges() {
    return  g.values().stream().flatMap(List::stream).collect(Collectors.toList());
}

Upvotes: 6

Related Questions