Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is Collectors.minBy() in Java?

abhilash

What is the Collectors class?

Collectors is a utility class that provides various implementations of reduction operations. These include grouping elements, collecting them to different collections, summarizing them according to various criteria, etc. The different functionalities in the Collectors class are usually used as the final operation on streams.

What is the minBy() method?

minBy() is a static method of the Collectors class that finds the minimum element of the input elements. It uses the passed comparator to do so.

The minBy method is defined in the Collectors class. The Collectors class is defined in the java.util.stream package. We can import the Collectors class using the following statement:

import java.util.stream.Collectors;

Syntax


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

Parameters

  • Comparator<? super T> comparator: The comparator to use for comparison.

Return value

This method returns a Collector that computes the minimum element using the given comparator.

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> minElement = stringStream.collect(Collectors.minBy(Comparator.naturalOrder()));

        System.out.println("Minimum element of the stream - " + (minElement.orElse("null")));
    }
}
Implementation of the minBy() method

Explanation

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

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring