作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我的 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/
我的 POJO 定义如下: class EmployeeDetails{ private String deptName; private Double salary; private Doub
我有一个具有值的对象列表,我想总结所有这些值。在 Java 8 中执行此操作的首选方法是什么? public static void main(String[] args) { List lo
基准测试在 intel core i5, Ubuntu 下运行 java version "1.8.0_144" Java(TM) SE Runtime Environment (build 1.8.
我是一名优秀的程序员,十分优秀!