javajava-streamcollectors

Join a Map of String, List into a single List excluding the String


I have a Map<String, List<MyObject>> myMap. How can I join all the List values into one List<MyObject>, excluding the String key?

I tried with this:

List<MyObject> list = new ArrayList<MyObject>(myMap.values())

but this does not work with collection keys.

Also thought of just iterating over the Maps and joining each list to a new list, but was hoping for a better way.


Solution

  • here is a possible way with streams

    map.values().stream().flatMap(Collection::stream).collect(Collectors.toList())