gpt4 book ai didi

Java 8 Lambda Collectors.summingLong 多列?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:41:27 26 4
gpt4 key购买 nike

我的 POJO 定义如下:

class EmployeeDetails{
private String deptName;
private Double salary;
private Double bonus;
...
}

目前,我有 Group By 'deptName' 的 lambda 表达式:

$set.stream().collect(Collectors.groupingBy(EmployeeDetails::getDeptName,
Collectors.summingLong(EmployeeDetails::getSalary));

问题 是否可以对不止一列进行求和?我需要在一个表达式中而不是多次计算两个字段薪水和奖金的总和?

SQL 表示为:

SELECT deptName,SUM(salary),SUM(bonus)
FROM TABLE_EMP
GROUP BY deptName;

最佳答案

您需要创建一个额外的类来保存您的 2 个汇总数字(薪水和奖金)。还有一个自定义收集器。

假设你有

private static final class Summary {
private double salarySum;
private double bonusSum;

public Summary() {
this.salarySum = 0;
this.bonusSum = 0;
}

@Override
public String toString() {
return "Summary{" +
"salarySum=" + salarySum +
", bonusSum=" + bonusSum +
'}';
}
}

用于持有金额。那么你需要一个这样的收集器:

private static class EmployeeDetailsSummaryCollector implements Collector<EmployeeDetails, Summary, Summary> {
@Override
public Supplier<Summary> supplier() {
return Summary::new;
}

@Override
public BiConsumer<Summary, EmployeeDetails> accumulator() {
return (summary, employeeDetails) -> {
summary.salarySum += employeeDetails.salary;
summary.bonusSum += employeeDetails.bonus;
};
}

@Override
public BinaryOperator<Summary> combiner() {
return (summary, summary1) -> {
summary.salarySum += summary1.salarySum;
summary.bonusSum += summary1.bonusSum;
return summary;
};
}

@Override
public Function<Summary, Summary> finisher() {
return Function.identity();
}

@Override
public Set<Characteristics> characteristics() {
return EnumSet.of(Collector.Characteristics.IDENTITY_FINISH);
}
}

通过这些类,您可以像这样收集结果

final List<EmployeeDetails> employees = asList(
new EmployeeDetails(/* deptName */"A", /* salary */ 100d, /* bonus */ 20d),
new EmployeeDetails("A", 150d, 10d),
new EmployeeDetails("B", 80d, 5d),
new EmployeeDetails("C", 100d, 20d)
);

final Collector<EmployeeDetails, Summary, Summary> collector = new EmployeeDetailsSummaryCollector();
final Map<String, Summary> map = employees.stream()
.collect(Collectors.groupingBy(o -> o.deptName, collector));
System.out.println("map = " + map);

打印这个:

map = {A=[salary=250.0, bonus=30.0], B=[salary=80.0, bonus=5.0], C=[salary=100.0, bonus=20.0]}

关于Java 8 Lambda Collectors.summingLong 多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42982029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com