如何使用流来展平和分组这个HashMap? [英] How to flatten and group this HashMap, using streams?
问题描述
鉴于字母到数字的映射,我想返回一个字符串列表,其中每个字符串是以逗号分隔的字母列表,按其关联的数字分组。
Given mapping of letters to numbers, I would like to return a list of Strings, where each String is a comma delimited list of the letters grouped by their associated number.
对于此地图
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 4);
map.put("D", 1);
map.put("E", 1);
map.put("F", 2);
我想返回一个包含以下内容的列表:
I would like to return a List containing:
"A,D,E" "B,F", "C"
有关如何使用1.8流媒体功能完成此任何建议吗?
Any suggestions how this can be accomplished using the 1.8 streaming functions?
推荐答案
这种方式没有在最初流式传输之后引用 map
,并最大限度地利用流媒体设施:
This way doesn't reference map
after it's initially streamed, and makes maximal use of the streaming facilities:
return map.entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Collectors.joining(","))))
.values().stream().collect(Collectors.toList());
或更简洁,但流量使用较少(感谢@Kartik):
Or more concisely, but with less usage of streams (thanks @Kartik):
return new ArrayList<>(map.entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Collectors.joining(","))))
.values());
在其中任何一个中,如果添加 TreeMap :: new
作为 Collectors.groupingBy
的两个现有参数之间的参数,内部部分将被排序。
In either of those, if you add TreeMap::new
as an argument between the two existing arguments to Collectors.groupingBy
, the "inside" pieces will be sorted.
这篇关于如何使用流来展平和分组这个HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!