Stream.min() returns the minimum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. min() is a terminal operation which combines stream elements and returns a summary result. So, min() is a special case of reduction. The method returns Optional instance.
Syntax :
Optional<T> min(Comparator<? super T> comparator)
Where, Optional is a container object which
may or may not contain a non-null value
and T is the type of objects
that may be compared by this comparator
Exception : This method throws NullPointerException if the minimum element is null.
Example 1 : Minimum from list of Integers.
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<Integer> list = Arrays.asList(- 9 , - 18 , 0 , 25 , 4 );
Integer var = list.stream().min(Integer::compare).get();
System.out.print(var);
}
}
|
Output :
-18
Example 2 : Reverse comparator to get maximum value using min() function.
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<Integer> list = Arrays.asList(- 9 , - 18 , 0 , 25 , 4 );
Optional<Integer> var = list.stream()
.min(Comparator.reverseOrder());
if (var.isPresent()){
System.out.println(var.get());
}
else {
System.out.println( "NULL" );
}
}
}
|
Output :
25
Example 3 : Comparing strings based on last characters.
import java.util.*;
class GFG {
public static void main(String[] args)
{
String[] array = { "Geeks" , "for" , "GeeksforGeeks" ,
"GeeksQuiz" };
Optional<String> MIN = Arrays.stream(array).min((str1, str2) ->
Character.compare(str1.charAt(str1.length() - 1 ),
str2.charAt(str2.length() - 1 )));
if (MIN.isPresent())
System.out.println(MIN.get());
else
System.out.println( "-1" );
}
}
|
Output :
for