简体   繁体   中英

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).

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM