In java 8 Stream class has static method iterate() which provide stream using that we can work like  normal for...loop. Java 9 Steam iterate provide additional predicate method to terminate stream iteration.

here are some examples  Stream.iterate() with Java 8 + Java 9

Example 1: Stream.iterate() + limit() (Java 8)

Iterate with two arguments, first is initial value and another is Unary operator for next element. limit() is for specify number of iteration.

Stream<Integer> integerStream = Stream.iterate(0, (Integer i) -> i + 1).limit(5);
integerStream.forEach(System.out::println);

Output:

0
1
2
3
4

Example 2: Stream.iterate() + Predicate() (Java 9)

Java 9 provides iterate() with three arguments those as follow:

  • Initial value (Seed value)
  • Predicate to check condition for iterator.
  • Unary Operator for next element
Stream<Integer> integerStream = Stream.iterate(0, (Integer i) -> (i < 5), (Integer i) -> i + 1);
       integerStream.forEach(System.out::println);

Output:

0
1
2
3
4

Example 3: Multiple Iterator example

Its are no concept for multiple iterator but i am giving example how we can generate pyramid using iterator.

Stream<Integer> row = Stream.iterate(0, (Integer i) -> i + 1).limit(5);
      row.forEach(integer -> {
          Stream<Integer> column = Stream.iterate(0, (Integer i) -> i + 1).limit(integer);
          column.forEach(System.out::print);
          System.out.println();
      });

Output:

0
01
012
0123

 

Example 4 : Stream iterator print event number between 1 to 10

Stream<Integer> integerStream = Stream.iterate(1, (Integer i) -> (i <= 10), (Integer i) -> i + 1);
        integerStream.filter(integer -> integer % 2 == 0).forEach(System.out::println);

Output:

2
4
6
8
10

 

 

 

References:

http://download.java.net/java/jdk9/docs/api/java/util/stream/Stream.html

 

 

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No
Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *