Java转置,Java8流:将值转换为列表的转置映射

该博客介绍了如何使用Java 8的流(Stream)和lambda表达式,将包含字符串键和字符串列表值的Map转换为整数键和列表值的Map。通过Stream.flatMap和groupingBy方法,实现了高效且简洁的代码实现。
摘要由CSDN通过智能技术生成

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 :

Input :

"Key-1" : 1,2,3,4

"Key-2" : 2,3,4,5

"Key-3" : 3,4,5,1

Expected output :

1 : "Key-1","Key-3"

2 : "Key-1","Key-2"

3 : "Key-1", "Key-2", "Key-3"

4 : "Key-1", "Key-2", "Key-3"

5 : "Key-2", "Key-3"

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> 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())));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值