How to find the sum of divisors using Java streams?

Viewed 801

I am trying to convert this function to use Java 8 new syntax. Hopefully it will reduce the number of lines and perhaps make things clearer.

public int divisorSum(int n) {
    int sum = 0;
    for(int i = 1; i <= n; i ++) {
        if(n % i == 0) {
            sum = Integer.sum(sum, i);
        }
    }
    return sum;
}

I tried this:

IntStream.range(0, n).forEach(i -> ... )

But according to a comment on this post by Tezra apparently it is not advisable to loop using lambdas.

4 Answers

Here's the Java 8 streams implementation:

public int divisorSum(int n) {
    return IntStream.rangeClosed(1, n).filter(i -> n % i == 0).sum();
}

Note that rangeClosed, like your example, includes n. range() excludes the second parameter (it would only include up to n-1).

You can achieve the same result using IntStream, filter and IntStream::sum that directly returns int since this stream is unboxed:

int sum = IntStream.rangeClosed(1, n).filter(i -> n % i == 0).sum();

You can do something like this

public static int divisorSum(int n) {
    return IntStream.rangeClosed(1, n)
            .filter(i -> n % i == 0)
            .sum();
}

This can be helpful.

int sum1 = java.util.stream.IntStream.range(1, n + 1).filter(x -> n % x == 0).reduce(0, (x, y) -> x + y);

or

int sum1 = java.util.stream.IntStream.range(1, n + 1).filter(x -> n % x == 0).sum();
Related