Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is Collectors.maxBy() in Java?

abhilash

The Collectors class

Collectors 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.

The maxBy() method

maxBy() 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;

Syntax


public static <T> Collector<T, ?, Optional<T>> maxBy(Comparator<? super T> comparator)

Parameters

  • Comparator<? super T> comparator: Used for comparison.

Return value

This method returns a Collector class that uses the given comparator to compute the maximum element.

Code

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")));
    }
}
Implementation of the "maxBy" method

Explanation

  • Lines 1–4: We import the relevant packages.
  • Line 10: We define a list of strings called stringList.
  • Line 12: We print stringList.
  • Line 14: We create a stream out of stringList.
  • Line 16: We use the maxBy method to get the maximum element. We pass the naturalOrder comparator as the argument to the maxBy method.
  • Line 18: We print the maximum element.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring