Thursday, October 23, 2025
HomeLanguagesJavaIntStream max() in Java with examples

IntStream max() in Java with examples

java.util.stream.IntStream in Java 8, deals with primitive ints. It helps to solve the problems like finding maximum value in array, finding minimum value in array, sum of all elements in array, and average of all values in array in a new way. IntStream max() returns an OptionalInt describing the maximum element of this stream, or an empty optional if this stream is empty.

Syntax :

OptionalInt() max()

Where, OptionalInt is a container object which 
may or may not contain a int value.

Example 1 :




// Java code for IntStream max()
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // creating a stream
        IntStream stream = IntStream.of(-9, -18, 54, 8, 7, 14, 3);
  
        // OptionalInt is a container object
        // which may or may not contain a
        // int value.
        OptionalInt obj = stream.max();
  
        // If a value is present, isPresent() will
        // return true and getAsInt() will
        // return the value
        if (obj.isPresent()) {
            System.out.println(obj.getAsInt());
        }
        else {
            System.out.println("-1");
        }
    }
}


Output :

54

Example 2 :




// Java code for IntStream max()
// to get the maximum value in range
// excluding the last element
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // To find maximum in given range
        IntStream stream = IntStream.range(50, 75);
  
        // storing the maximum value in variable
        // if it is present, else show -1.
        int maximum = stream.max().orElse(-1);
  
        // displaying the maximum value
        System.out.println(maximum);
    }
}


Output :

74

Example 3 :




// Java code for IntStream max()
// to get the maximum value in range
// excluding the last element
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // To find maximum in given range
        IntStream stream = IntStream.range(50, 50);
  
        // storing the maximum value in variable
        // if it is present, else show -1.
        int maximum = stream.max().orElse(-1);
  
        // displaying the maximum value
        System.out.println(maximum);
    }
}


Output :

-1
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS