如何在Java 8中扁平化地图内的列表

问题描述:

如何从整数的映射转到字符串列表,例如:

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

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

扁平化的字符串列表,例如:

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

Java 8 中?

您可以将flatMap用于以下值:

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

或者,如果您要使用地图条目,则可以使用Holger指出的代码:

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());