如何在Java 8中扁平化地图内的列表 [英] How to flatten a list inside a map in Java 8
本文介绍了如何在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());
这篇关于如何在Java 8中扁平化地图内的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文