作为java函数式编程的初学者,我需要一些考虑到三个参数即list.parallelStream().collect(supplier, accumulator, combiner)的collect()方面的帮助。如何计算列表中提到的所有员工的工资总和?
public class SumMethodsOfCollectorclass {
public static void main(String[] args) {
List<Employee> list = new ArrayList<>();
list.add(new Employee(6, "Nick", 27, "Software Engineer", 44000f));
list.add(new Employee(9, "Tom", 23, "Civil Engineer", 32000f));
list.add(new Employee(3, "Jon", 29, "Mechanical Engineer", 37000f));
list.add(new Employee(4, "Harry", 21, "Surgeon", 55000f));
list.add(new Employee(8, "Don", 25, "Laywer", 50000f));
list.add(new Employee(7, "Marry", 20, "Police", 29000f));
list.add(new Employee(2, "Angel", 22, "Professor", 35000f));
list.add(new Employee(1, "Kate", 23, "Teacher", 29000f));
list.add(new Employee(5, "Evan", 22, "Pilot", 44000f));
sumOfAgeOfAllEmployees(list);
sumOfSalaryOfAllEmployees(list);
}
private static void sumOfAgeOfAllEmployees(List<Employee> list) {
Integer result = list.stream().parallel().collect(Collectors.summingInt(i -> i.getAge()));
System.out.println("The sum of age of all employees - " + result);
}
private static void sumOfSalaryOfAllEmployees(List<Employee> list) {
// to get the sum of salary of all the employees
list.parallelStream().collect(supplier, accumulator, combiner)
}
}发布于 2020-10-09 20:00:55
您可以使用原子整数来执行这种可变的约简。这可能意味着顺序流中的额外成本,但它是如何工作的:
private static int sumOfSalaryOfAllEmployees(List<Employee> list) {
AtomicInteger res = list.stream().mapToInt(Employee::getSalary)
.collect(AtomicInteger::new,
AtomicInteger::addAndGet,
(ai1, ai2) -> ai1.addAndGet(ai2.get()));
return res.get();
}您可能还希望使用一个自定义类来累加值(如果AtomicInteger中的同步是不必要的开销):
private static class IntHolder {
private int value;
public IntHolder() {
}
public IntHolder(int val) {
this.value = val;
}
public int getValue() {
return value;
}
public void add(int val) {
this.value += val;
}
public void accumulate(IntHolder other) {
this.value += other.value;
}
}然后:
private static int sumOfSalaryOfAllEmployees(List<Employee> list) {
IntHolder res = list.stream().mapToInt(Employee::getSalary)
.collect(IntHolder::new, IntHolder::add, IntHolder::accumulate);
return res.getValue();
}发布于 2020-10-09 20:04:32
基本上,您的供应商需要返回一个可变的结果容器。
一个AtomicInteger或者一个定制的IntHolder类就可以了。或者来自apache commons-lang3的MutableInt:
MutableInt sum = list.parallelStream().collect(
() -> new MutableInt(0),
(sum1, employee) -> sum1.add(employee.getSalary()),
(sum1, sum2) -> sum1.add(sum2.intValue())
);https://stackoverflow.com/questions/64279351
复制相似问题