Collectors minBy() method in Java 8


The minBy() method of the Collectors class in Java 8 returns a Collector that produces the minimum element according to a given Comparator, described as an Optional<T>

The syntax is as follows

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

Here, the parameters

  • T - Type of the input elements
  • comparator – For comparing elements
  • Options <T>- A container object that may or may not contain a non-null value

To work with Collectors class in Java, import the following package

import java.util.stream.Collectors;

The following is an example to implement mainBy() method in Java

Example

 Live Demo

import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("45", "71", "25", "87");
      Optional<String> op = stream.collect(Collectors.minBy(String::compareTo));
      if (op.isPresent()) {
         System.out.println(op.get());
      } else {
         System.out.println("Nothing!");
      }
   }
}

Output

25

Updated on: 30-Jul-2019

293 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements