Saturday, August 15, 2020

Java 8 Stream.iterate() VS Stream.random() - Infinite Streams


import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamGenerateVSIterate {

    public static void main(String[] args) {

        // Example to generate 10 random numbers from 0 to 20.
        Supplier<Integer> infiniteStream1 = () -> new Random().nextInt(20);

        List<Integer> randomNumbers = Stream.generate(infiniteStream1).limit(15).collect(Collectors.toList());

        System.out.println("10 random numbers list : " + randomNumbers);

        // Example to generate 10 random numbers from 0 to 20.
        Stream<Integer> infiniteStream2 = Stream.iterate(0, i -> i + 1);

        List<Integer> first10Numbers = infiniteStream2.limit(15).collect(Collectors.toList());

        System.out.println("first 10 numbers list : " + first10Numbers);

    }
}

Output:

15 random numbers list : [18, 3, 11, 4, 11, 5, 19, 3, 4, 5, 11, 7, 6, 0, 0]
first 15 numbers list : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]



No comments:

Post a Comment