Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression for supplier to generate IntStream

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
like image 640
Shiva Avatar asked Dec 01 '18 15:12

Shiva


People also ask

Which of the following is valid lambda for the supplier interface for string typed?

Option D is valid because it takes a String argument and returns an int value.

Which of the functional interface represents a supplier of results?

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() .

What does IntStream return?

IntStream filter(IntPredicate predicate) Returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation.


1 Answers

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);
    
like image 191
Nikolas Charalambidis Avatar answered Oct 21 '22 07:10

Nikolas Charalambidis