Yassine Ben Hamida :
I want to extract a List<E>
from a Map<String,List<E>>
(E
is a random Class) using stream()
.
I want a simple one-line method using java 8's stream.
What I have tried until now :
HashMap<String,List<E>> map = new HashMap<>();
List<E> list = map.values(); // does not compile
list = map.values().stream().collect(Collectors.toList()); // does not compile
Ousmane D. :
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());