Home > Java > javaTutorial > 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
Release: 2023-08-20 18:49:03
forward
1428 people have browsed it

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>
Copy after login

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);
   }
}
Copy after login

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>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template