user10824969
user10824969

Reputation:

IntStream instead of for loop without condition

In answer to my question user nullpointer suggested here - https://stackoverflow.com/a/53905940/10824969 how for loops can be converted to stream way using IntStream.iterate.

I had a similar for loop condition with which I iterate

void printMultiples(int number, int threshold) {
    for (int i = number; ; i = i + threshold) {
        if (i < threshold) {
            break;
        } else {
            System.out.println(i);
        }
    }
}

trying to convert this to

IntStream.iterate(number, i -> i + number).forEach(System.out::println);
                                              ^^
// Non-short-circuit operation consumes the infinite stream

there is a warning with IDE in above code. I also tried to check for multiples using IntStream.range, the below prints all the numbers instead

IntStream.range(number, threshold).forEach(System.out::println);

Upvotes: 1

Views: 710

Answers (1)

Naman
Naman

Reputation: 31878

You can filter your stream as

IntStream.range(number, threshold)
    .filter(i -> i % number == 0) // only those divisible by number
    .forEach(System.out::println);

Or if Java-9 or above is an option, you can possibly use

IntStream.iterate(number, i -> i < threshold, i -> i + number)
        .forEach(System.out::println);

Or more appropriately as it sounds like a while loop, use Intstream.takeWhile as :

IntStream.iterate(number, i -> i + number)
        .takeWhile(i -> i < threshold)
        .forEach(System.out::println);

Upvotes: 5

Related Questions