0

I have a HashMap<Foo, ArrayList<Bar>> map with the following structure:

|-- a
|   |-- a1
|   |-- a2
|   `-- a3
|
`-- b
    |-- b1
    |-- b2
    `-- b3

where a and b are objects of the type Foo and a1, a2, etc. objects of the type Bar.

What I want to have is a List<Bar> with the following structure:

|-- a1
|-- a2
|-- a3
|-- b1
|-- b2
`-- b3

Right now I have this code:

ArrayList<Bar> tempList = new ArrayList<>();
map.values().forEach(tempList::addAll);
return tempList;

But this feels a bit clumsy and inelegant. How can I achieve this using the standard Java API, preferably with java.util.Stream (or lambda expressions)?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
linkD
  • 121
  • 13
  • 1
    See also http://stackoverflow.com/questions/31056919/concatenate-the-string-values-of-all-maps-in-a-list or http://stackoverflow.com/questions/35682522/convert-mapstring-navigablemaplong-collectionstring-to-liststring-usin – Tunaki Dec 04 '16 at 17:23

1 Answers1

3
List<Bar> bars = map.values()
                    .stream()
                    .flatMap(Collection::stream)
                    .collect(Collectors.toList());
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255