如何使用Java Streams API合并Map的列表和Lists值? [英] How to merge lists of Map with Lists values using Java Streams API?

查看:128
本文介绍了如何使用Java Streams API合并Map的列表和Lists值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过Xp减少 Map< X,List< String>> 分组并同时加入所有列表值,以便我拥有 Map< Integer,List< String>> 最后?

How can I reduce the Map<X, List<String>> grouping by the X.p and join all the list values at the same time, so that I have Map<Integer, List<String>> at the end?

这就是我尝试过的远:

class X {
    int p;
    int q;
    public X(int p, int q) { this.p = p; this.q = q; }
}
Map<X, List<String>> x = new HashMap<>();
x.put(new X(123,5), Arrays.asList("A","B"));
x.put(new X(123,6), Arrays.asList("C","D"));
x.put(new X(124,7), Arrays.asList("E","F"));
Map<Integer, List<String>> z = x.entrySet().stream().collect(Collectors.groupingBy(
    entry -> entry.getKey().p, 
    mapping(Map.Entry::getValue, 
        reducing(new ArrayList<>(), (a, b) -> { a.addAll(b); return a; }))));
System.out.println("z="+z);

但结果是:z = {123 = [E,F,A,B,C, D],124 = [E,F,A,B,C,D]}。

But the result is: z={123=[E, F, A, B, C, D], 124=[E, F, A, B, C, D]}.

我想要z = {123 = [A,B,C ,D],124 = [E,F]}

I want to have z={123=[A, B, C, D], 124=[E, F]}

推荐答案

您正在使用还原收藏家不正确。第一个参数必须是还原操作的标识值。但是你通过向它添加值来修改它,这完美地解释了结果:所有值都被添加到相同的 ArrayList ,这应该是不变的标识值。

You are using the reducing collector incorrectly. The first argument must be an identity value to the reduction operation. But you are modifying it by adding values to it, which perfectly explains the result: all values are added to the same ArrayList which is expected to be the invariant identity value.

你想要做的是 可变减少 Collectors.reducing 是不合适。您可以使用方法 Collector.of(...)

What you want to do is a Mutable reduction and Collectors.reducing is not appropriate for that. You may create an appropriate collector using the method Collector.of(…):

Map<Integer, List<String>> z = x.entrySet().stream().collect(groupingBy(
    entry -> entry.getKey().p, Collector.of(
        ArrayList::new, (l,e)->l.addAll(e.getValue()), (a,b)->{a.addAll(b);return a;})));

这篇关于如何使用Java Streams API合并Map的列表和Lists值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆