Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
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
Advertisements
