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
Or you can use this
Something like this if you're bound to use
Stream.generate
specifically :Edit: Using
IntStream.generate
, you can perform it asNote: 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:You might want to use rather
IntStream::range
:Another solution might be using the
IntStream.iterate
where you can control the increment comfortably using theIntUnaryOperator
:As said, the
Stream::generate
is suitable for the constant streams or random elements. The random element might be obtained using the classRandom
so here you might want to get an increment usingAtomicInteger
: