Collectors
classCollectors
is a utility class that provides various implementations of reduction operations such as grouping, collecting, and summarizing elements.
The different functionalities in the Collectors
class are used as final operations on streams.
maxBy()
methodmaxBy()
is a static method of the Collectors
class that is used to find the maximum element of the input elements using the passed comparator.
The maxBy
method is defined in the Collectors
class. The Collectors
class is defined in the java.util.stream
package.
To import the Collectors
class, use the following import statement:
import java.util.stream.Collectors;
public static <T> Collector<T, ?, Optional<T>> maxBy(Comparator<? super T> comparator)
Comparator<? super T> comparator
: Used for comparison.This method returns a Collector
class that uses the given comparator to compute the maximum element.
import java.util.Arrays;import java.util.Comparator;import java.util.List;import java.util.Optional;import java.util.stream.Collectors;import java.util.stream.Stream;public class Main {public static void main(String[] args){List<String> stringList = Arrays.asList("educative", "io", "edpresso");System.out.println("Stream before modification - " + stringList);Stream<String> stringStream = stringList.stream();Optional<String> maxElement = stringStream.collect(Collectors.maxBy(Comparator.naturalOrder()));System.out.println("Maximum element of the stream - " + (maxElement.orElse("null")));}}
stringList
.stringList
.stringList
.maxBy
method to get the maximum element. We pass the naturalOrder comparator as the argument to the maxBy
method.