java 8 stream group by和sum double [英] java 8 stream group by and summing double

查看:2379
本文介绍了java 8 stream group by和sum double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是java 8中的新手,所以我的方法可能是错误的。

I am very new to streams in java 8 so my approach could be wrong.

我有2个对象如下

object1 {
    BigDecimal amount;
    Code1 code1;
    Code2 code2;
    Code3 code3;
    String desc;
}

object2 {
    BigDecimal amount;
    Code1 code1;
    Code2 code2;
    Code3 code3;
}

所以我想收集所有object1,其中code1&& code2&& code3是相同的,然后将金额加到object2列表中。

So I want to collect all object1 where code1 && code2 && code3 are same and then sum the amount add it to object2 list.

我没有代码来执行它...我想编写一个代码来执行job
我正在尝试从 http:// docs中实现一些功能.oracle.com / javase / tutorial / collections / interfaces / map.html

I do not have a code to do it...I want to write a code that does the job I am trying to implement something from http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html

或按部门计算所有工资的总和:

Or compute the sum of all salaries by department:

// Compute sum of salaries by department
Map<Department, Integer> totalByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.summingInt(Employee::getSalary)));


推荐答案

感谢JB Nizet指出我正确的方向。
我必须修改我的object2

Thanks to JB Nizet for pointing me in the right direction. I had to modify my object2

public class CodeSummary {
    Double amount;
    CodeKey key;
//getters and setters

}
public class CodeKey {
    String code1;
    String code2;
    String code3;
//getters and setters

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof CodeKey)) return false;

        CodeKey that = (CodeKey) o;

        if (!code1.equals(that.code1)) return false;
        if (!code2.equals(that.code2)) return false;
        if (!code3.equals(that.code3)) return false;

        return true;
    }

@Override
public int hashCode() {
    int result = code1.hashCode();
    result = 31 * result + code2.hashCode();
    result = 31 * result + code3.hashCode();
    return result;
}

}

迭代object1并填充object2。一旦我填充了我的object2(现在是codeSymmary)。我可以使用下面的方法来完成这项工作。

iterate over object1 and populate object2. Once i had my object2 (now codeSymmary) populated. i could use the method below to do the job.

        Map<CodeKey, Double> summaryMap = summaries.parallelStream().
                collect(Collectors.groupingBy(CodeSummary::getKey,
                Collectors.summingDouble(CodeSummary::getAmount))); // summing the amount of grouped codes.

如果有人使用此作为示例。然后确保覆盖密钥对象中的equal和hashcode函数。否则分组将无效。

If anyone is using this as an example. then make sure you override the equal and hashcode function in your key object. else grouping will not work.

希望这有助于某人

这篇关于java 8 stream group by和sum double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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