Home  >  Article  >  Java  >  What is the importance of iterate() method of Stream API in Java 9?

What is the importance of iterate() method of Stream API in Java 9?

WBOY
WBOYforward
2023-08-20 18:49:031401browse

Stream API的iterate()方法在Java 9中的重要性是什么?

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.

Grammar

<strong>static <T> Stream<T> iterate(T seed, Predicate<? super T><!--? super T--> hasNext, UnaryOperator<T> next)</strong>

Example

Chinese translation is:

Example

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);
   }
}

Output

<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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete