我对 java 8 中的流非常陌生,所以我的方法可能是错误的。
我有 2 个对象如下
object1 {
BigDecimal amount;
Code1 code1;
Code2 code2;
Code3 code3;
String desc;
}
object2 {
BigDecimal amount;
Code1 code1;
Code2 code2;
Code3 code3;
}
所以我想收集所有 code1 && code2 && code3 相同的 object1,然后将其金额求和添加到 object2 列表中。
我没有代码可以做到这一点...我想编写一个可以完成这项工作的代码
我正在尝试实施一些东西http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
或者按部门计算所有工资的总和:
// Compute sum of salaries by department
Map<Department, Integer> totalByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.summingInt(Employee::getSalary)));
感谢 JB Nizet 为我指明了正确的方向。
我必须修改我的对象2
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)。我可以使用下面的方法来完成这项工作。
Map<CodeKey, Double> summaryMap = summaries.parallelStream().
collect(Collectors.groupingBy(CodeSummary::getKey,
Collectors.summingDouble(CodeSummary::getAmount))); // summing the amount of grouped codes.
如果有人用这个作为例子。然后确保您覆盖关键对象中的 equal 和 hashcode 函数。否则分组将不起作用。
希望这对某人有帮助
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)