Amir Afghani
Amir Afghani

Reputation: 38531

Java8 reducing a stream

I have the following methods:

static IntStream streamedDivisors(final int n) {
    return IntStream.range(2, n).parallel().filter(input -> n % input == 0);
}

static int streamedPhi(final int n) {
    return streamedDivisors(n).reduce(0, x -> x * x);
}

and I'm getting a compilation error in streamedPhi indicating that I have incompatible parameter types in my lambda expression. Can someone help me make sense of this? I'm essentially trying to take the divisors of a given number n, and aggregate a number on some function I defined (in this case, squaring the number).

Upvotes: 1

Views: 341

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

Your compilation issue is due to the fact that IntBinaryOperator#applyAsInt(int, int) takes two arguments. You were only declaring/providing one.

As stated in the comments and after looking at the javadoc of IntStream#reduce(int, IntBinaryOperator) , you aren't actually applying a valid reduction. It's not immediately clear to me what you mean by and aggregate a number on some function I defined but Brian has some suggestions.

Upvotes: 5

Related Questions