我有以下要求,这可能很简单,但作为初学者,我想在这里寻求帮助。
class Employee{
String department;
int age;
int salary;
}
class Foo{
double averagingAge;
double averagingSalary;
}
我想按部门分组使用groupingBy(department, collector(Foo))
. 任何人都可以帮忙吗?
我有以下要求,这可能很简单,但作为初学者,我想在这里寻求帮助。
class Employee{
String department;
int age;
int salary;
}
class Foo{
double averagingAge;
double averagingSalary;
}
我想按部门分组使用groupingBy(department, collector(Foo))
. 任何人都可以帮忙吗?
custom collector is the solution in java8:
class Foo{
private double ageSum;
private double salarySum;
private long ageCount;
private long salaryCount;
public double getAgeAvg(){
return ageCount != 0 ? ageSum/ageCount : 0.0;
}
public double getSalaryAvg(){
return salaryCount != 0 ? salarySum/salaryCount : 0.0;
}
}
自定义收集器:
Map<Department, Foo> groupByResult = empList.stream().collect(groupingBy(department,
Collector.of(
() -> {
return new Foo();
},
(result, emp) -> {
result.setAgeSum(result.getAgeSum() + emp.getAge());
result.setSalarySum(result.getSalarySum() + emp.getSalarySum());
result.setSalaryCount((result.getSalaryCount()) + 1);
result.setAgeCount(result.getAgeCount() + 1);
},
(result1, result2) -> {
result1.setSalarySum(result1.getSalarySum() + result2.getSalarySum());
result1.setAgeSum(result1.getAgeSum() + result2.getAgeSum());
result1.setAgeCount(result1.getAgeCount() + result2.getAgeCount());
result1.setSalaryCount(result1.getSalaryCount() + result2.getSalaryCount());
return result1;
}
));