Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 557
Yassine Ben Hamida Avatar asked Jan 05 '19 17:01

Yassine Ben Hamida


People also ask

Can HashMap store list?

HashMap and List in Java. Java provides us with different data structures with various properties and characteristics to store objects. Among those, HashMap is a collection of key-value pairs that maps a unique key to a value. Also, a List holds a sequence of objects of the same type.

How do I iterate over a map string ArrayList object >>?

Different ways to iterate through Map :Using keySet(); method and Iterator interface. Using entrySet(); method and for-each loop. Using entrySet(); method and Iterator interface. Using forEach(); in Java 1.8 version.


1 Answers

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()); 
like image 156
Ousmane D. Avatar answered Sep 24 '22 00:09

Ousmane D.