我正在尝试理解这个Java Stream方法
<R> R collect(Supplier<R> supplier,
BiConsumer<R, ? super T> accumulator,
BiConsumer<R, R> combiner);
下面的代码应该给出结果 55 put 而不是 0 被打印出来。 有人可以向我解释一下出了什么问题以及如何更改它以便打印 55 吗?
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Create a supplier that returns a new mutable result container, in this case an Integer accumulator.
Supplier<Integer> supplier = () -> 0;
// Create an accumulator that adds the square of the current element to the result container.
BiConsumer<Integer, Integer> accumulator = (result, element) -> result += element * element;
// Create a combiner that adds two result containers together.
BiConsumer<Integer, Integer> combiner = (result1, result2) -> result1 += result2;
// Collect the results of the reduction operation into a single Integer value.
Integer sumOfSquares = numbers.stream().collect(supplier, accumulator, combiner);
System.out.println(sumOfSquares); // 55
您正在处理不可变的整数/整数。因此,累加器和组合器都不会改变结果。因此保持为 0。
您可以通过使用像 AtomicInteger 这样的可变对象来执行操作并使用完成器将其转换回 Integer 来避免此问题:
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Create a supplier that returns a new mutable result container, in this case an Integer accumulator.
Supplier<AtomicInteger> supplier = () -> new AtomicInteger(0);
// Create an accumulator that adds the square of the current element to the result container.
BiConsumer<AtomicInteger, Integer> accumulator = (result, element) -> result.getAndAdd(element * element);
// Create a combiner that adds two result containers together.
BinaryOperator<AtomicInteger> combiner = (result1, result2) -> {
result1.set(result1.getAndAdd(result2.get()));
return result1;
};
Function<AtomicInteger, Integer> finisher = AtomicInteger::get;
// Collect the results of the reduction operation into a single Integer value.
Integer sumOfSquares = numbers.stream().collect(Collector.of(supplier, accumulator, combiner, finisher));
System.out.println(sumOfSquares); // 55
}