Rodrigo
Rodrigo

Reputation: 321

How to flatten a list inside a map in Java 8

How can I go from a map of integers to lists of strings such as:

<1, ["a", "b"]>,
<2, ["a", "b"]>

To a flattened list of strings such as:

["1-a", "1-b", "2-a", "2-b"]

in Java 8?

Upvotes: 8

Views: 11525

Answers (2)

Naman
Naman

Reputation: 31868

You can use flatMap on values as:

map.values()
   .stream()
   .flatMap(List::stream)
   .collect(Collectors.toList());

Or if you were to make use of the map entries, you can use the code as Holger pointed out :

map.entries()
   .stream()
   .flatMap(e -> e.getValue().stream().map(s -> e.getKey() + s))
   .collect(Collectors.toList());

Upvotes: 10

Samuel Philipp
Samuel Philipp

Reputation: 11032

You can just use this:

List<String> result = map.entrySet().stream()
        .flatMap(entry -> entry.getValue().stream().map(string -> entry.getKey() + "-" + string))
        .collect(Collectors.toList());

This iterates over all the entries in the map, joins all the values to their key and collects it to a new List.

The result will be:

[1-a, 1-b, 2-a, 2-b]

Upvotes: 2

Related Questions