In Java 8, the iterate() method of Stream API accepts seed and unary operator as parameters. Since the stream becomes infinite, developers need to add explicit termination conditions using methods such as limit, findFirst, and findAny. In Java 9, the iterate() method of Stream API adds a new parameter, predicate, which is used to specify the conditions for interrupting the stream.
<strong>static <T> Stream<T> iterate(T seed, Predicate<? super T><!--? super T--> hasNext, UnaryOperator<T> next)</strong>
import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.List; public class StreamIterateMethodTest { public static void main(String args[]) { List<Integer> numbers1 = Stream.<strong>iterate</strong>(1, i -> i+1) <strong> // with two arguments</strong> .<strong>limit</strong>(10) .<strong>collect</strong>(Collectors.toList()); System.out.println("In Java 8:" + numbers1); <strong>List<Integer></strong> numbers2 = Stream.<strong>iterate</strong>(1, i -> i <= 10, i -> i+1) <strong>// with three arguments</strong> <strong>.collect</strong>(Collectors.toList()); System.out.println("In Java 9:" + numbers2); } }
<strong>In Java 8:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In Java 9:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</strong>
The above is the detailed content of What is the importance of iterate() method of Stream API in Java 9?. For more information, please follow other related articles on the PHP Chinese website!