Exploring a generator-style approach in Java with Supplier and IntStream.generate().

Transcribed from the original LinkedIn image post.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.function.Function;
import java.util.function.IntSupplier;
import java.util.stream.IntStream;

class Day30 {
    public static void main(String[] args) {
        Function<Integer, Integer> squareFunction = integer -> integer * integer;

        SupplierProvider squareSupplier = new SupplierProvider(squareFunction);

        IntStream myStream = IntStream.generate(squareSupplier);
        myStream.limit(10).forEach(System.out::println);
        System.out.println("---------------- INTERVAL ----------------");
        IntStream stream = IntStream.generate(squareSupplier);
        stream.limit(5).forEach(System.out::println);
    }

    static class SupplierProvider implements IntSupplier {
        int i = 0;
        Function<Integer, Integer> function;

        public SupplierProvider(Function<Integer, Integer> function) {
            this.function = function;
        }

        @Override
        public int getAsInt() {
            i++;
            return function.apply(i);
        }
    }
}

The original LinkedIn graphic is preserved below.

Day 30 LinkedIn post