How can i change the code and use stream() instead with functional programming?

Viewed 75

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);
2 Answers
int sum = IntStream.range(0, 1000)
                   .filter(i -> i % 3 == 0 || i % 5 == 0)
                   .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);
Related