基于密钥按给定列表分组并在相同列表中收集的有效方法java 8 [英] Efficient way to group by a given list based on a key and collect in same list java 8

查看:141
本文介绍了基于密钥按给定列表分组并在相同列表中收集的有效方法java 8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

class A{
  String property1;
  String property2;
  Double property3;
  Double property4;
}

因此property1和property2是关键。

So the property1 and property2 is the key.

class Key{
      String property1;
      String property2; 
}

我已经有以下A的列表:

I already have a list of A like below:

List<A> list=new ArrayList<>();

我想通过使用密钥进行分组并添加到另一个A列表中以避免出现多个列表中具有相同键的项目:

I want to group by using the key and add to another list of A in order to avoid having multiple items with same key in the list:

Function<A, Key> keyFunction= r-> Key.valueOf(r.getProperty1(), r.getProperty2());

但是当我做分组时,我必须得到一个property3和property4的平均值。

But then while doing group by I have to take a sum of property3 and average of property4.

我需要一种有效的方法。

I need an efficient way to do it.

注意:我跳过了给定类的方法。

Note: I have skipped the methods of the given classes.

推荐答案

收集到地图是不可避免的因为你想要 group 的东西。这样做的一种蛮力方式是:

Collecting to a Map is unavoidable since you want to group things. A brute-force way to do that would be :

yourListOfA
      .stream()
      .collect(Collectors.groupingBy(
             x -> new Key(x.getProperty1(), x.getProperty2()),
             Collectors.collectingAndThen(Collectors.toList(),
                   list -> {
                        double first = list.stream().mapToDouble(A::getProperty3).sum();
                        // or any other default
                        double second = list.stream().mapToDouble(A::getProperty4).average().orElse(0D);
                        A a = list.get(0);
                        return new A(a.getProperty1(), a.getProperty2(), first, second);
            })))
     .values();

这可能会略有改善,例如 Collectors.collectingAndThen 只迭代 List 一次,因为需要一个自定义收集器。写一个并不复杂......

This could be slightly improved for example in the Collectors.collectingAndThen to only iterate the List once, for that a custom collector would be required. Not that complicated to write one...

这篇关于基于密钥按给定列表分组并在相同列表中收集的有效方法java 8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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