IntStream iterate in steps

前端 未结 7 1557
悲&欢浪女
悲&欢浪女 2020-12-03 07:41

How do you iterate through a range of numbers (0-100) in steps(3) with IntStream?

I tried iterate, but this never stops executing.

IntS         


        
7条回答
  •  没有蜡笔的小新
    2020-12-03 08:25

    Actually you can also achieve the same results with a combination of peek and allMatch:

    IntStream.iterate(0, n -> n + 3).peek(n -> System.out.printf("%d,", n)).allMatch(n -> n < 100 - 3);
    

    This prints

    0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,

    But nevertheless, this one is faster:

    IntStream.range(0, 100 / 3 + 1).map(x -> x * 3).forEach((x) -> System.out.printf("%d,", x));
    

    Java 9 Update:

    Now the same iteration easier to achieve with Java 9:

    Stream.iterate(0, i -> i <= 100, i -> 3 + i).forEach(i -> System.out.printf("%d,", i));
    

提交回复
热议问题