0

I have an object of type Map<String,Map<String,List<String>>> . I need to extract the list of Strings. Can someone help me how can I do it in Java Streams ?

Naman
  • 27,789
  • 26
  • 218
  • 353
Prakhar
  • 92
  • 12

1 Answers1

2

You'd want to use flatMap. For example:

List<String> list = myMap.values().stream()
        .map(Map::values)
        .flatMap(Collection::stream)
        .flatMap(Collection::stream)
        .collect(Collectors.toList());

I suggest you go over the docs, as there's different ways to achieve this, with different performance implications. There's also libraries like Eclipse Collections that can help you accomplish the same.

Here's a great answer on how to flatten a list of lists, which explains different tradeoffs and approaches: How can I turn a List of Lists into a List in Java 8?

jlhonora
  • 10,179
  • 10
  • 46
  • 70
  • 1
    Or avoiding the `map` operation with lambda in `flatMap` such as - `myMap.values().stream() .flatMap(innerMap -> innerMap.values() .stream().flatMap(Collection::stream)) .collect(Collectors.toList());` – Naman Feb 27 '20 at 02:00