问题描述
我将键映射为String,值映射为List。列表可以有10个唯一值。我需要将此映射转换为键为Integer,将值转换为List。示例如下:
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中的streams / 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.
-Thanks。
推荐答案
一个想法可能是从原始地图生成所有价值密钥对,然后按这些值对密钥进行分组:
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流:将值转换为列表的转置映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!