Lambda expression for supplier to generate IntStream

倖福魔咒の 提交于 2019-12-04 04:16:47

Something like this if you're bound to use Stream.generate specifically :

IntStream inStream = Stream.generate(new AtomicInteger(1)::getAndIncrement)
        .limit(10)
        .mapToInt(t -> t);
inStream.forEach(System.out::println);

Edit: Using IntStream.generate, you can perform it as

IntStream.generate(new AtomicInteger(1)::getAndIncrement).limit(10);

Note: A better solution in terms of the API design would definitely be to make use of Stream.iterate for such a use case.

The Stream::generate is not suitable for this issue. According to the documentation:

This is suitable for generating constant streams, streams of random elements, etc.

  • You might want to use rather IntStream::range:

    IntStream intStream = IntStream.range(1, 11);
    intStream.forEach(System.out::println);
    
  • Another solution might be using the IntStream.iterate where you can control the increment comfortably using the IntUnaryOperator:

    IntStream intStream = IntStream.iterate(1, i -> i+1).limit(10);
    intStream.forEach(System.out::println);
    
  • As said, the Stream::generate is suitable for the constant streams or random elements. The random element might be obtained using the class Random so here you might want to get an increment using AtomicInteger:

    AtomicInteger atomicInteger = new AtomicInteger(1);
    IntStream intStream = Stream.generate(atomicInteger::getAndIncrement).limit(10);
    intStream.forEach(System.out::println);
    

Or you can use this

IntStream.iterate(1, i -> i + 1)
 .limit(10)
 .forEach(System.out::println);  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!