我试图理解这个Java Stream方法

<R> R collect(Supplier<R> supplier,
              BiConsumer<R, ? super T> accumulator,
              BiConsumer<R, R> combiner);

下面的代码应该给出作为结果的55把而不是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

推荐答案

您正在处理的int/int不是可变的.因此,累加器和组合器都不会改变结果.因此,它保持0.

你可以通过使用一个可变对象(如Atomicupon)来完成操作,并使用一个finisher将其转换回NTFS来避免这个问题:

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 AtomicInteger 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.getAndAdd(result2.get());
        return result1;
    };

    //Create a Finisher to get the Integer value
    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
}

Java相关问答推荐

是否有一种格式模式,可以在除0之外的数字前面有正负符号?

基于仅存在于父级中的字段查询子文档?

如何转换Tue Feb 27 2024 16:35:30 GMT +0800 String至ZonedDateTime类型""

不推荐使用的Environment.getExternalStorageDirectory().getAbsolutePath()返回的值不同于新的getExternalFilesDir(空)?

如何确定springboot在将json字段转换为Dto时如何处理它?

如何在运行时动态创建表(使用Java、JPA、SprringBoot)

Jenv-相同的Java版本,但带有前缀

如果按钮符合某些期望,如何修改它的文本?

JNI:将代码打包成自包含的二进制文件

Cordova Android Gradle内部版本组件不兼容

EXCEL中的公式单元格显示#NAME?

try 使用预准备语句占位符获取信息时出现Try-With-Resources错误

JOLT根据值删除并保留其余的json键

如何调整JButton的大小以适应图标?

如何对存储为字符串的大数字数组进行排序?

Win32函数的JNA绑定DwmGetColorizationColor返回E_INVALIDARG错误

如果c不为null,Arrays.sort(T[]a,Comparator<;?super T>;c)是否会引发ClassCastException?

java 11上出现DateTimeParseException,但java 8上没有

什么是;u〃;平均值;jdku;在java开发工具包中?

Java 8 中 ByteBuffer 和 BitSet 的奇怪行为