我昨天问了一个关于 HashMap 扁平化/分组的问题。我得到了很好的回应,建议我这样做。
return new ArrayList<>(map.entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Collectors.joining(","))))
.values())
但是,我希望逗号分隔字符列表按字母顺序排序。评论建议我尝试使用 TreeMap::new
作为 groupingBy()
的参数,但是当我尝试这样做时,我的字符列表仍然未排序:
return new ArrayList<>(map.entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
TreeMap::new,
Collectors.mapping(Map.Entry::getKey, Collectors.joining(","))))
.values())
以下是我最初的问题,其中包含该帖子的链接。
给定字母到数字的映射,我想返回一个字符串列表,其中每个字符串都是按其关联数字分组的字母的逗号分隔列表。
对于这张 map
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);
我想返回一个包含以下内容的列表:
"A,D,E" "B,F", "C"
有什么建议可以使用 1.8 流功能来实现这一点吗?
最佳答案
在执行操作之前将 map 转换为 TreeMap
,键将在输出中按顺序排列。
// * here
return new ArrayList<>(new TreeMap(map).entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
TreeMap::new,
Collectors.mapping(Map.Entry::getKey, Collectors.joining(","))))
.values())
关于java - 如何使用流对这个 HashMap 进行排序,同时对其进行展平/分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55070584/