简体   繁体   English

如何使用 Java 流找到除数的总和?

[英]How to find the sum of divisors using Java streams?

I am trying to convert this function to use Java 8 new syntax.我正在尝试将此 function 转换为使用 Java 8 新语法。 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.但根据 Tezra 对这篇文章的评论,显然不建议使用 lambdas 循环。

Here's the Java 8 streams implementation:这是 Java 8 个流的实现:

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

Note that rangeClosed , like your example, includes n .请注意, rangeClosed与您的示例一样,包括n range() excludes the second parameter (it would only include up to n-1 ). range()不包括第二个参数(它最多只能包括n-1 )。

You can achieve the same result using IntStream , filter and IntStream::sum that directly returns int since this stream is unboxed:您可以使用直接返回intIntStreamfilterIntStream::sum获得相同的结果,因为此 stream 未装箱:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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