问题
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?
回答1:
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());
回答2:
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]
来源:https://stackoverflow.com/questions/55519967/how-to-flatten-a-list-inside-a-map-in-java-8