I want to extract a List
from a Map
(E
is a random Class) using stream()
.
I
map.values()
returns a Collection<List<E>>
not a List<E>
, if you want the latter then you're required to flatten the nested List<E>
into a single List<E>
as follows:
List<E> result = map.values()
.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
You can use Collection.stream with flatMap
as:
Map<String, List<E>> map = new HashMap<>(); // program to interface
List<E> list = map.values()
.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
or use a non-stream version as:
List<E> list = new ArrayList<>();
map.values().forEach(list::addAll)
Here's an alternate way to do it with Java-9 and above:
List<E> result = map.values()
.stream()
.collect(Collectors.flatMapping(List::stream, Collectors.toList()));
Simply use :-
map.values().stream().flatMap(List::stream).collect(Collectors.toList());
In addition to other answers:
List<E> result = map.values()
.stream()
.collect(ArrayList::new, List::addAll, List::addAll);
This could also do the trick.
Or use forEach
map.forEach((k,v)->list.addAll(v));
or as Aomine commented use this
map.values().forEach(list::addAll);