Stream.generate()

Description

generate(Supplier<T> s) uses Supplier to generate an infinite sequential unordered stream.

Example

The following code prints five random numbers.


import java.util.stream.Stream;
// w  ww .j  a v a2s. co m
public class Main {
  public static void main(String[] args) {
    Stream.generate(Math::random)
    .limit(5)
    .forEach(System.out::println);

  }
}

The code above generates the following result.

Example 2

To generate a stream in which the next element is generated based on the previous one, you will need to use a Supplier that stores the last generated element.

The following code keeps the last value in a static varaible.


import java.util.stream.Stream;
/* ww  w.  j a v a  2s.  c  om*/
public class Main {
  public static void main(String[] args) {
    Stream.generate(Main::next)
    .limit(5)
    .forEach(System.out::println);

  }
  
  static int i=0;
  private static int next(){
    i++;
    return i;
  }
}

The code above generates the following result.





















Home »
  Java Streams »
    Tutorial »




Java Streams Tutorial