In Java 8, the iterate() method has been introduced and it has only two parameters and will help us to create an infinite stream.
Content:
1 |
public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) |
Example:
1 2 3 4 5 6 7 8 9 10 |
package com.huongdanjava.javastream; import java.util.stream.Stream; public class Example { public static void main(String[] args) { Stream.iterate(1, i -> i + 1).forEach(System.out::println); } } |
When running the above example, you will see that a Stream object contains endless numbers beginning at 1.
With Java 9, the iterate() method has improved by adding another parameter, the Predicate interface, which allows us to stop these endless numbers based on the conditions we define with the Predicate interface.
Content:
1 |
public static<T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) |
Example:
1 2 3 4 5 6 7 8 9 10 |
package com.huongdanjava.javastream; import java.util.stream.Stream; public class Example { public static void main(String[] args) { Stream.iterate(1, i -> i < 10, i -> i + 1).forEach(System.out::println); } } |
Result: