1

I have a multimap Map<T,List<L>> map and I need a list with all the values of the values from the map, namely List<L>. With map.values() I get a List<List<L>>, but thats not what I want.

Does someone know a clean solution without looping?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
melanzane
  • 483
  • 1
  • 6
  • 16

1 Answers1

3

If you are using Java 8, you could collect all L values from all List<L>s in a single List<L> by Stream#flatMap:

final List<L> list = map
        // get a Collection<List<L>>
        .values()
        // make a stream from the collection
        .stream()
        // turn each List<L> into a Stream<L> and merge these streams
        .flatMap(List::stream)
        // accumulate the result into a List
        .collect(Collectors.toList());

Otherwise, a for-each approach with Collection#addAll can be applied:

final List<L> list = new ArrayList<>();

for (final List<L> values : map.values()) {
    list.addAll(values);
}
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142