如何修改代码并使用`stream()`以及函数式编程呢?

huangapple go评论58阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年9月16日 21:20:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63920993.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定