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
Option D is valid because it takes a String argument and returns an int value.
Interface Supplier<T> Represents a supplier of results. There is no requirement that a new or distinct result be returned each time the supplier is invoked. This is a functional interface whose functional method is get() .
IntStream filter(IntPredicate predicate) Returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With