LongStream generate() method in Java

LongStream generate(LongSupplier s) returns an infinite sequential unordered stream where each element is generated by the provided LongSupplier(a supplier of long-valued results). This is suitable for generating constant streams, streams of random elements, etc.

Syntax :

static LongStream generate(LongSupplier s)

Parameters :

  1. LongStream : a sequence of primitive long-valued elements.
  2. LongSupplier : a supplier of long-valued elements.
  3. s : LongSupplier for generated elements.

Return Value : a new infinite sequential unordered LongStream.

Example 1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for LongStream.generate()
// to generate an infinite sequential
// unordered LongStream
import java.util.*;
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // using LongStream.generate() method
        // to generate 7 random Integer values
        LongStream stream = LongStream.generate(()
               -> { return (long)(Math.random() * 10000); });
  
        // Displaying the randomly generated values
        stream.limit(7).forEach(System.out::println);
    }
}

chevron_right


Output :

4377
6200
9920
6015
7879
7887
8792

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.