How to get a List<E> from a HashMap<String,List<E>>

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());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35303&siteId=1