Ank*_*kit 1 grouping dictionary java-8 java-stream collectors
我对 Java 8 中的流很陌生,所以我的方法可能是错误的。
我有 2 个对象如下
object1 {
BigDecimal amount;
Code1 code1;
Code2 code2;
Code3 code3;
String desc;
}
object2 {
BigDecimal amount;
Code1 code1;
Code2 code2;
Code3 code3;
}
Run Code Online (Sandbox Code Playgroud)
所以我想收集 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)));
Run Code Online (Sandbox Code Playgroud)
感谢 JB Nizet 为我指明了正确的方向。我不得不修改我的 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;
}
}
Run Code Online (Sandbox Code Playgroud)
遍历 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.
Run Code Online (Sandbox Code Playgroud)
如果有人以此为例。然后确保覆盖 key 对象中的 equal 和 hashcode 函数。否则分组将不起作用。
希望这有助于某人
| 归档时间: |
|
| 查看次数: |
8186 次 |
| 最近记录: |