Lambda expression for supplier to generate IntStream

  • A+
Category:Languages

How do I replace the Supplier code here with lambda expression

IntStream inStream = Stream.generate(new Supplier<Integer>() {     int x= 1;     @Override     public Integer get() {         return x++ ;     } }).limit(10).mapToInt(t -> t.intValue()); inStream.forEach(System.out::println); 

The output of above piece of code is:

1 2 3 4 5 6 7 8 9 10 

 


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

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: