英文:
How can i change the code and use stream() instead with functional programming?
问题
以下是使用 stream()
和函数式编程重写的代码:
long sum = IntStream.range(1, 1000)
.filter(i -> i % 3 == 0 || i % 5 == 0)
.sum();
System.out.println(sum);
这段代码使用了 Java 的 IntStream
,首先生成了从1到999的整数流,然后筛选出能被3或5整除的数字,最后对这些数字求和。
英文:
How can i change the code and use stream() instead with functional programming?
Here is the code I want to change using stream() and functional programming:
int sum=0;
for(int i=0; i<1000; i++) {
if(i%3==0 || i%5==0) {
sum=sum+i;
}
}
System.out.println(sum);
Here is my attempt but doesn't give the same answer as I want:
long counting = Stream.iterate(1, x-> x+1)
.filter(i-> i % 3==0 || i%5==0)
.limit(1000)
.mapToInt(n -> n)
.sum();
System.out.println(counting);
答案1
得分: 6
int sum = IntStream.range(0, 1000)
.filter(i -> i % 3 == 0 || i % 5 == 0)
.sum();
英文:
int sum = IntStream.range(0, 1000)
.filter(i -> i % 3 == 0 || i % 5 == 0)
.sum();
答案2
得分: 2
有一种方法是:
int sum = Stream.iterate(0, n -> n + 1)
.limit(1000)
.filter(i -> i % 3 == 0 || i % 5 == 0)
.reduce(0, Integer::sum);
System.out.println(sum);
英文:
One way to do so would be:
int sum = Stream.iterate(0, n -> n + 1)
.limit(1000)
.filter(i -> i % 3 == 0 || i % 5 == 0)
.reduce(0, Integer::sum);
System.out.println(sum);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论