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

  • A+
Category:Languages

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 

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: