Reputation: 1541
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
Is there a way to use stream for this?
Upvotes: 1
Views: 120
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