Saturday, August 15, 2020

Java 8 Stream.iterate() Infinite Streams Example

Java 8 Example program to generate the first 10 numbers from the infinite stream using Stream.iterate()Method


package com.javaprogramto.java8.streams.infinite;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamIterateExample {

    public static void main(String[] args) {

        // Creating a infinite Stream
        Stream<Integer> integerInfiniteStream = Stream.iterate(1, i -> i +1);

        List<Integer> first10Numbers = integerInfiniteStream.limit(10).collect(Collectors.toList());

        System.out.println("integerInfiniteStream with limit 10 : "+first10Numbers);

    }
}

Output:

integerInfiniteStream with limit 10 : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Java 8 Example program to generate the 10 ten even numbers from the infinite stream using Stream.iterate()Method


package com.javaprogramto.java8.streams.infinite;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamIterateExample {

    public static void main(String[] args) {

        // Creating a infinite Stream
        Stream<Integer> even10Numbers = Stream.iterate(0, i -> i +2);

        List<Integer> first10Numbers = even10Numbers.limit(10).collect(Collectors.toList());

        System.out.println("even10Numbers with limit 10 : "+first10Numbers);

    }
}

Output:

even10Numbers with limit 10 : [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]



No comments:

Post a Comment