Stream.max() returns the maximum 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. max() is a terminal operation which combines stream elements and returns a summary result. So, max() is a special case of reduction. The method returns Optional instance.
Syntax :
Optional<T> max(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 maximum element is null.
Example 1 :
import java.util.*;
import java.util.Optional;
import java.util.Comparator;
class GFG {
public static void main(String[] args)
{
List<Integer> list = Arrays.asList(- 9 , - 18 , 0 , 25 , 4 );
System.out.print( "The maximum value is : " );
Integer var = list.stream().max(Integer::compare).get();
System.out.print(var);
}
}
|
Output :
The maximum value is : 25
Example 2 :
import java.util.*;
import java.util.Optional;
import java.util.Comparator;
class GFG {
public static void main(String[] args)
{
List<Integer> list = Arrays.asList(- 9 , - 18 , 0 , 25 , 4 );
Optional<Integer> var = list.stream()
.max(Comparator.reverseOrder());
if (var.isPresent()) {
System.out.println(var.get());
}
else {
System.out.println( "-1" );
}
}
}
|
Output :
-18
Example 3 :
import java.util.*;
import java.util.Optional;
import java.util.Comparator;
class GFG {
public static void main(String[] args)
{
List<String> list = Arrays.asList( "G" , "E" , "E" , "K" ,
"g" , "e" , "e" , "k" );
String MAX = list.stream().max(Comparator.
comparing(String::valueOf)).get();
System.out.println( "Maximum element in the "
+ "stream is : " + MAX);
}
}
|
Output :
Maximum element in the stream is : k
Example 4 :
import java.util.*;
import java.util.Optional;
import java.util.Comparator;
class GFG {
public static void main(String[] args)
{
String[] array = { "Geeks" , "for" , "GeeksforGeeks" ,
"GeeksQuiz" };
Optional<String> MAX = Arrays.stream(array).max((str1, str2) ->
Character.compare(str1.charAt(str1.length() - 1 ),
str2.charAt(str2.length() - 1 )));
if (MAX.isPresent())
System.out.println(MAX.get());
else
System.out.println( "-1" );
}
}
|
Output :
GeeksQuiz
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
06 Dec, 2018
Like Article
Save Article