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.iterat...

问题:

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

回答1:

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);
  • 发表于 2018-12-31 19:32
  • 阅读 ( 296 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除