Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a java equivalent to C#'s .Aggregate(foo) method?

Tags:

java

c#

I'm trying to implement the accept answer in this question in java:

Greatest Common Divisor from a set of more than 2 integers

But I don't know how to implement the aggregate function.

like image 877
Ogen Avatar asked Mar 14 '26 09:03

Ogen


1 Answers

There is a one-liner when using 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);
    }
}

Output is "7". The aggregate function is called a reduction.

Alternative: The lambda can also be written with a method reference.

public static int gcd(int[] ints) {
    return Arrays.stream(ints).reduce(GCD::gcd).getAsInt();
}
like image 118
Seelenvirtuose Avatar answered Mar 15 '26 23:03

Seelenvirtuose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!