How to flatten a list inside a map in Java 8

孤街浪徒 提交于 2021-02-04 18:17:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!