java lambda group,我如何像Lambda一样使用Lambda在Java中将List的值分组

I want to group values of a map based on the key. Let's say

Map map1 = new TreeMap();

map1.put("D", 3);

map1.put("B", 2);

map1.put("C", 1);

Map map2 = new TreeMap();

map2.put("A", 13);

map2.put("B", 22);

map2.put("C", 12);

Map map3 = new TreeMap();

map3.put("A", 33);

map3.put("B", 32);

map3.put("C", 32);

Map> map = new HashMap >();

map.put(1,map1);

map.put( 2, map2);

map.put(3, map3);

System.out.println(map);

I want to group values in the map based on the keys: Output should be ["A","B","C"]:[2,3], ["D","B","C"]:[1]

So what I have done:

Map, List> newMap = new HashMap, List>();

for (Integer item : map) {

Map currentValue = map.get(item);

List oldItemKeySet = newMap.get(currentValue.keySet());

newMap.put(currentValue.keySet(), (oldItemKeySet == null) ? 1 : oldItemKeySet.put());

}

But it doesn't work out, can anyone help here.

PS: In Python, these things can be done with itertools.groupby or reduce, but i am still don't knoww how to do it perfectly in Java

解决方案

If I understand well, you want to group the identical key set of the maps you added in the last map associated with the original key.

import static java.util.stream.Collectors.groupingBy;

import static java.util.stream.Collectors.mapping;

import static java.util.stream.Collectors.toList;

...

Map, List> newMap =

map.entrySet()

.stream()

.collect(groupingBy(e -> e.getValue().keySet(),

mapping(Map.Entry::getKey, toList())));

From the last map, you get the stream of entries (which is a Stream>). There you group the entries by the key set of their map's values.

Then you map the values of the resulting map using a downstream collector, which collects the keys of the original entries in a List.

Output:

{[A, B, C]=[2, 3], [B, C, D]=[1]}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值