Thursday, September 25, 2025
HomeLanguagesJavaOptionalInt stream() method in Java with examples

OptionalInt stream() method in Java with examples

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

Syntax:

public IntStream stream()

Parameters: This method accepts nothing.

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

Below programs illustrate stream() method:
Program 1:




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


Output:

Program 2:




// Java program to demonstrate
// OptionalInt.stream() method
  
import java.util.OptionalInt;
import java.util.stream.IntStream;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // create a OptionalInt
        OptionalInt opInt = OptionalInt.empty();
  
        // get value as stream
        IntStream out = opInt.stream();
  
        // print value
        if (out.count() == 0)
            System.out.println("opInt is empty");
    }
}


Output:

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

RELATED ARTICLES

Most Popular

Dominic
32319 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6681 POSTS0 COMMENTS
Nicole Veronica
11854 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6794 POSTS0 COMMENTS
Ted Musemwa
7070 POSTS0 COMMENTS
Thapelo Manthata
6753 POSTS0 COMMENTS
Umr Jansen
6761 POSTS0 COMMENTS