Java8 streams : Transpose map with values as list(Java8流:将值作为列表的转置映射)
问题描述
我的映射键为字符串,值为列表.列表可以有 10 个唯一值.我需要将此映射转换为键为整数,值为列表.示例如下:
I have map with key as String and value as List. List can have 10 unique values. I need to convert this map with key as Integer and value as List. Example as below :
输入:
Key-1":1,2,3,4
"Key-1" : 1,2,3,4
Key-2":2,3,4,5
"Key-2" : 2,3,4,5
Key-3":3,4,5,1
"Key-3" : 3,4,5,1
预期输出:
1 : "Key-1","Key-3"
1 : "Key-1","Key-3"
2 : "Key-1","Key-2"
2 : "Key-1","Key-2"
3 : Key-1"、Key-2"、Key-3"
3 : "Key-1", "Key-2", "Key-3"
4 : Key-1"、Key-2"、Key-3"
4 : "Key-1", "Key-2", "Key-3"
5 : "Key-2", "Key-3"
5 : "Key-2", "Key-3"
我知道使用 for 循环我可以实现这一点,但我需要知道这可以通过 java8 中的流/lamda 来完成.
I am aware that using for loops i can achieve this but i needed to know can this be done via streams/lamda in java8.
-谢谢.
推荐答案
一个想法可能是从原始映射生成所有值-键对,然后按这些值对键进行分组:
An idea could be to generate all value-key pairs from the original map and then group the keys by these values:
import java.util.AbstractMap.SimpleEntry;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
...
Map<Integer, List<String>> transposeMap =
map.entrySet()
.stream()
.flatMap(e -> e.getValue().stream().map(i -> new SimpleEntry<>(i, e.getKey())))
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
这篇关于Java8流:将值作为列表的转置映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java8流:将值作为列表的转置映射
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01