英文:
How to find the sum of divisors using Java streams?
问题
我正在尝试将这个函数转换为使用Java 8的新语法。希望能减少代码行数,或许能使代码更清晰。
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;
}
我尝试了以下内容:
IntStream.range(0, n).forEach(i -> ... )
但根据这个帖子中Tezra的评论,显然不建议使用lambda进行循环。
英文:
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.
答案1
得分: 4
这是Java 8流的实现:
public int divisorSum(int n) {
return IntStream.rangeClosed(1, n).filter(i -> n % i == 0).sum();
}
注意,rangeClosed
与你的示例一样,包括 n
。range()
则排除第二个参数(它只会包括到 n-1
)。
英文:
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
).
答案2
得分: 3
你可以使用IntStream
、filter
和IntStream::sum
来实现相同的结果,这个流直接返回int
,因为这个流是拆箱的:
int sum = IntStream.rangeClosed(1, n).filter(i -> n % i == 0).sum();
英文:
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();
答案3
得分: 3
你可以像这样做:
public static int divisorSum(int n) {
return 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();
}
答案4
得分: 1
这可能会有所帮助。
int sum1 = java.util.stream.IntStream.range(1, n + 1).filter(x -> n % x == 0).reduce(0, (x, y) -> x + y);
或者
int sum1 = java.util.stream.IntStream.range(1, n + 1).filter(x -> n % x == 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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论