以下是一个Java函数,它可以进行流处理的功能:

import java.util.stream.Stream;

public class StreamProcessingFunctions {

    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);

        // Filter function - filters out odd numbers
        Stream<Integer> filteredStream = stream.filter(n -> n % 2 == 0);

        // Map function - squares each number
        Stream<Integer> mappedStream = filteredStream.map(n -> n * n);

        // Reduce function - adds up all the squared even numbers
        int sum = mappedStream.reduce(0, Integer::sum);

        System.out.println('Sum of squared even numbers: ' + sum);
    }

}

这个函数使用了Java 8中的流式API。首先,我们创建了一个整数流,然后使用filter函数过滤出偶数。接着,我们使用map函数对每个偶数进行平方操作。最后,我们使用reduce函数将所有平方偶数加起来,得到它们的和。

Java流处理函数示例:过滤、映射和求和

原文地址: https://www.cveoy.top/t/topic/nsRR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录