Functional Programming With Java 简明教程
Functional Programming with Java - Reducing
在函数式编程中,归约是一种将值的流缩小为一个结果的技术,方法是对所有值应用一个函数。Java 从 8 开始在 Stream 类中提供了 reduce() 函数。流具有内置的归约方法,如 sum()、average() 和 count(),它们适用于流的所有元素,并返回单个结果。
In functional programming, reducing is a technique to reduce a stream of values to a single result by apply a function on all the values. Java provides reduce() function in a Stream class from Java 8 onwards. A stream has inbuilt reducing methods like sum(), average(), count() as well which works on all elements of the stream and returns the single result.
以下示例演示了归约的工作原理。
Following example shows how Reducing works.
import java.util.stream.IntStream;
public class FunctionTester {
public static void main(String[] args) {
//1 * 2 * 3 * 4 = 24
int product = IntStream.range(1, 5)
.reduce((num1, num2) -> num1 * num2)
.orElse(-1);
//1 + 2 + 3 + 4 = 10
int sum = IntStream.range(1, 5).sum();
System.out.println(product);
System.out.println(sum);
}
}