How to use collect method with three params i.e "collect(supplier, accumulator, combiner)" to add integers in a list

huangapple go评论70阅读模式
英文:

How to use collect method with three params i.e "collect(supplier, accumulator, combiner)" to add integers in a list

问题

以下是您要求的代码部分翻译结果:

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, "Lawyer", 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) {
        // 获取所有员工的薪水总和
        Float salarySum = list.parallelStream()
                .map(Employee::getSalary)
                .reduce(0f, Float::sum);
        System.out.println("The sum of salary of all employees - " + salarySum);
    }
}

请注意,代码中的职位 "Lawyer" 已经进行了修正,另外代码中的注释也已翻译。

英文:

Being a beginner to java functional programming, I need some help on collect() that takes into consideration the three params i.e list.parallelStream().collect(supplier, accumulator, combiner). How can i calculate sum of salary all employees mentioned in the list.

public class SumMethodsOfCollectorclass {
public static void main(String[] args) {
List&lt;Employee&gt; list = new ArrayList&lt;&gt;();
list.add(new Employee(6, &quot;Nick&quot;, 27, &quot;Software Engineer&quot;, 44000f));
list.add(new Employee(9, &quot;Tom&quot;, 23, &quot;Civil Engineer&quot;, 32000f));
list.add(new Employee(3, &quot;Jon&quot;, 29, &quot;Mechanical Engineer&quot;, 37000f));
list.add(new Employee(4, &quot;Harry&quot;, 21, &quot;Surgeon&quot;, 55000f));
list.add(new Employee(8, &quot;Don&quot;, 25, &quot;Laywer&quot;, 50000f));
list.add(new Employee(7, &quot;Marry&quot;, 20, &quot;Police&quot;, 29000f));
list.add(new Employee(2, &quot;Angel&quot;, 22, &quot;Professor&quot;, 35000f));
list.add(new Employee(1, &quot;Kate&quot;, 23, &quot;Teacher&quot;, 29000f));
list.add(new Employee(5, &quot;Evan&quot;, 22, &quot;Pilot&quot;, 44000f));
sumOfAgeOfAllEmployees(list);
sumOfSalaryOfAllEmployees(list);
}
private static void sumOfAgeOfAllEmployees(List&lt;Employee&gt; list) {
Integer result = list.stream().parallel().collect(Collectors.summingInt(i -&gt; i.getAge()));
System.out.println(&quot;The sum of age of all employees - &quot; + result);
}
private static void sumOfSalaryOfAllEmployees(List&lt;Employee&gt; list) {
// to get the sum of salary of all the employees
list.parallelStream().collect(supplier, accumulator, combiner)
}
}

答案1

得分: 1

你可以使用原子整数(AtomicInteger)执行这种可变缩减操作。这可能会在顺序流中增加额外的成本,但以下是它的工作方式:

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;
    }
}

然后

```java
private static int sumOfSalaryOfAllEmployees(List<Employee> list) {
    IntHolder res = list.stream().mapToInt(Employee::getSalary)
        .collect(IntHolder::new, IntHolder::add, IntHolder::accumulate);

    return res.getValue();
}
英文:

You can perform this mutable reduction using an atomic integer. This may mean additional cost in a sequential stream, but here's how it would work:

private static int sumOfSalaryOfAllEmployees(List&lt;Employee&gt; list) {
AtomicInteger res = list.stream().mapToInt(Employee::getSalary)
.collect(AtomicInteger::new, 
AtomicInteger::addAndGet, 
(ai1, ai2) -&gt; ai1.addAndGet(ai2.get()));
return res.get();
}

You may also want a custom class to use for the accumulation of values (if synchronization in AtomicInteger is unnecessary overhead):

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;
}
}

Then:

private static int sumOfSalaryOfAllEmployees(List&lt;Employee&gt; list) {
IntHolder res = list.stream().mapToInt(Employee::getSalary)
.collect(IntHolder::new, IntHolder::add, IntHolder::accumulate);
return res.getValue();
}

答案2

得分: 1

基本上,您的供应商需要返回一个可变的结果容器。

可以使用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())
);
英文:

Basically, your supplier needs to return a mutable result container.

An AtomicInteger will do, or an custom IntHolder class. Or a MutableInt from apache commons-lang3:

    MutableInt sum = list.parallelStream().collect(
() -&gt; new MutableInt(0),
(sum1, employee) -&gt; sum1.add(employee.getSalary()),
(sum1, sum2) -&gt; sum1.add(sum2.intValue())
);

huangapple
  • 本文由 发表于 2020年10月9日 19:40:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64279351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定