是否有一个等同于C#的.Aggregate(foo)方法的java?

时间:2014-07-25 06:00:03

标签: java c#

我正试图在java中的这个问题中实现接受答案:

Greatest Common Divisor from a set of more than 2 integers

但我不知道如何实现聚合函数。

1 个答案:

答案 0 :(得分:6)

使用Java 8时有一个单行程序:

public class GCD {
    public static void main(String[] args) {
        int[] ints = { 42, 21, 14, 70 };
        System.out.println(gcd(ints));
    }
    public static int gcd(int[] ints) {
        return Arrays.stream(ints).reduce((a, b) -> gcd(a, b)).getAsInt();
    }
    public static int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
}

输出是" 7"。聚合函数称为 reduction

替代方案:lambda也可以使用方法引用编写。

public static int gcd(int[] ints) {
    return Arrays.stream(ints).reduce(GCD::gcd).getAsInt();
}