Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Importance of iterate() method of Stream API in Java 9?\\n
In Java 8, the iterate() method of Stream API takes the seed and the unary operator as arguments. As stream becomes infinite, it makes the developer add explicit termination conditions by using limit, findFirst, findAny and etc. In Java 9, the iterate() method of Stream API has added a new argument, a predicate that takes the condition to break the flow.
Syntax
static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)
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.iterate(1, i -> i+1) // with two arguments
.limit(10)
.collect(Collectors.toList());
System.out.println("In Java 8:" + numbers1);
List<Integer> numbers2 = Stream.iterate(1, i -> i <= 10, i -> i+1) // with three arguments
.collect(Collectors.toList());
System.out.println("In Java 9:" + numbers2);
}
}
Output
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]
Advertisements
