Thursday, January 29, 2026
HomeLanguagesJavaLongStream min() in Java with examples

LongStream min() in Java with examples

java.util.stream.LongStream in Java 8, deals with primitive longs. 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. LongStream min() returns an OptionalLong describing the minimum element of this stream, or an empty optional if this stream is empty.

Syntax :

OptionalLong() min()

Where, OptionalLong is a container object which 
may or may not contain a long value.

Example 1 :




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


Output :

-18

Example 2 :




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


Output :

50

Example 3 :




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


Output :

-1
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32477 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7221 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6916 POSTS0 COMMENTS