Stream.iterate()

Description

The iterate() method takes two arguments: a seed and a function.

A seed is the first element of the stream. The second element is generated by applying the function to the first element. The third element is generated by applying the function on the second element.

Therefore the elements are: seed, f(seed), f(f(seed)), f(f(f(seed)))....

The following code creates a stream of natural numbers:

Stream<Long> naturalNumbers = Stream.iterate(1L, n -> n + 1);

The limit(long maxSize) operation is an intermediate operation that produces another stream.

Example

The following code creates a stream of the first 10 natural numbers:


import java.util.stream.Stream;
//from   www.  j  a  v a  2s .  co m
public class Main {
  public static void main(String[] args) {
    Stream<Long> tenNaturalNumbers = Stream.iterate(1L, n  ->  n  + 1)
        .limit(10);

    tenNaturalNumbers.forEach(System.out::println);
  }
}

The code above generates the following result.

Example 2

The following code filters the values generated from an iterate function.


import java.util.stream.Stream;
/*w ww  .  j a  va2s . co m*/
public class Main {
  public static void main(String[] args) {
    Stream.iterate(2L, n  ->  n  + 1)
    .filter(Main::isOdd)
    .limit(5)
    .forEach(System.out::println);
  }
  public static boolean isOdd(long number) {
    if (number % 2 == 0) {
      return false;
    }
    return true;
  }
}

The code above generates the following result.

Example 3

To discard some elements from a stream, use the skip operation.

The skip(long n), an intermediate operation, skips the first n elements of the stream.

The following code uses skip to skip the first 100 odd number:


import java.util.stream.Stream;
/*from www .ja v a 2s. c  o  m*/
public class Main {
  public static void main(String[] args) {
    Stream.iterate(2L, n  ->  n  + 1)
    .filter(Main::isOdd)
    .skip(100)
    .limit(5)
    .forEach(System.out::println);
  }
  public static boolean isOdd(long number) {
    if (number % 2 == 0) {
      return false;
    }
    return true;
  }
}

The code above generates the following result.





















Home »
  Java Streams »
    Tutorial »




Java Streams Tutorial