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
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With