IntStream iterate in steps

前端 未结 7 1546
悲&欢浪女
悲&欢浪女 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:30

    If you are ok adding a library dependency, the IntInterval class in Eclipse Collections has the step function I think you are looking for. I tried a few different approaches converting IntInterval to an IntStream, since the original question asked for IntStream. Here are the solutions I came up with using IntInterval and then converting it to an IntStream.

    IntInterval interval = IntInterval.zeroTo(99).by(3);
    interval.each(System.out::print);
    
    IntStream.of(interval.toArray()).forEach(System.out::print);
    
    IntStream.Builder builder = IntStream.builder();
    interval.each(builder::add);
    builder.build().forEach(System.out::print);
    
    IntStream.generate(interval.intIterator()::next)
        .limit(interval.size()).forEach(System.out::print);
    

    IntInterval is inclusive on the from and to like IntStream.rangeClosed().

    Note: I am a committer for Eclipse Collections

提交回复
热议问题