Collectors.groupby for Maplt;String,Listlt;Stringgt;(Collectors.groupby 用于地图lt;String,Listlt;Stringgt;)
问题描述
如果解决方案非常明显,请原谅我,但我似乎无法弄清楚如何做到这一点
Forgive me if the solution is very obvious but I can't seem to figure out how to do this
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("b1", "a1");
map.put("b2", "a2");
map.put("b3", "a1");
Map<String, List<String>> mm = map.values().stream().collect(Collectors.groupingBy(m -> m));
System.out.println(mm);
}
我想根据 hashmap 中的值进行分组.我希望输出为 {a1=[b1, b3], a2=[b2]}
但它目前以 {a1=[a1, a1], a2=[a2]}
I want to group by based on values in hashmap. I want the output to be {a1=[b1, b3], a2=[b2]}
but it is currently coming as {a1=[a1, a1], a2=[a2]}
推荐答案
目前,您正在流式传输地图值(我认为这是一个错字),根据您需要的输出,您应该流式传输地图 entrySet
并使用基于映射值的 groupingBy
和基于映射键的 mapping
作为下游收集器:
Currently, you're streaming over the map values (which I assume is a typo), based on your required output you should stream over the map entrySet
and use groupingBy
based on the map value's and mapping
as a downstream collector based on the map key's:
Map<String, List<String>> result = map.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey,
Collectors.toList())));
你也可以通过 forEach
+ computeIfAbsent
执行这个没有流的逻辑:
You could also perform this logic without a stream via forEach
+ computeIfAbsent
:
Map<String, List<String>> result = new HashMap<>();
map.forEach((k, v) -> result.computeIfAbsent(v, x -> new ArrayList<>()).add(k));
这篇关于Collectors.groupby 用于地图<String,List<String>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Collectors.groupby 用于地图<String,List<String>
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01