Collectors minBy() method in Java 8

Java 8Object Oriented ProgrammingProgramming

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
raja
Updated on 30-Jul-2019 22:30:25

Advertisements