- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Collectors maxBy() method in Java 8
The maxBy() method of the Collectors class in Java 8 returns a Collector that produces the maximal element according to a given Comparator, described as an Optional<T>.
The syntax is as follows
static <T> Collector<T,?,Optional<T>> maxBy(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 maxBy() 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("4", "7", "25", "87"); Optional<String> op = stream.collect(Collectors.maxBy(String::compareTo)); if (op.isPresent()) { System.out.println(op.get()); } else { System.out.println("Nothing!"); } } }
Output
87
Advertisements