OptionalLong stream() method in Java with examples

The stream() method help us to get Long value contain by OptionalLong as LongStream.If a value is present, method returns a sequential LongStream containing only that value, otherwise returns an empty LongStream.

Syntax:

public LongStream stream()

Parameters: This method accepts nothing.



Return value: This method returns the optional value as an LongStream.

Below programs illustrate stream() method:
Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// OptionalLong.stream() method
  
import java.util.OptionalLong;
import java.util.stream.LongStream;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // create a OptionalLong
        OptionalLong opLong
            = OptionalLong.of(163252382159472124L);
  
        // get value as stream
        LongStream out = opLong.stream();
  
        // print value
        System.out.print("Value: ");
        out.forEach(System.out::print);
    }
}

chevron_right


Output:

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// OptionalLong.stream() method
  
import java.util.OptionalLong;
import java.util.stream.LongStream;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // create a empty OptionalLong
        OptionalLong opLong = OptionalLong.empty();
  
        // get value as stream
        LongStream out = opLong.stream();
  
        // print value
        System.out.print("length of Long Stream: "
                         + out.count());
    }
}

chevron_right


Output:

References: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalLong.html#empty()




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.