The Collectors.maxBy()
method is used to find the maximum element from a stream based on a certain comparator. It returns an Optional
which contains the maximum element according to the provided comparator, or an empty Optional
if there are no elements in the stream.
Here’s a simple example where we have a list of integers, and we want to find the biggest integer:
package org.kodejava.stream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class MaxByDemo {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> maxNumber = numbers.stream()
.collect(Collectors.maxBy(Comparator.naturalOrder()));
maxNumber.ifPresent(System.out::println);
}
}
In this example:
- We create a Stream from the list of integers.
- We then use
Collectors.maxBy(Comparator.naturalOrder())
to get the maximum number.Comparator.naturalOrder()
is a shortcut forComparator.comparing(Function.identity())
. Collectors.maxBy()
returns anOptional
because the stream could be empty.- We print the maximum number if it exists.
When you run this program, it will print “5” because 5 is the biggest number in the list.
Keep in mind that if the stream is empty, maxNumber
will be an empty Optional
, and nothing will be printed.
Latest posts by Wayan (see all)
- How do I create a servlet filter to make secure cookies? - April 18, 2024
- How do I configure secure cookies using web.xml? - April 18, 2024
- How do I create a table with multiple header in iText 8? - March 16, 2024