Problem:
Java's max function in lambda expressions and streams typically returns an arbitrary element when multiple candidates tie for the maximum value. This can be undesirable when the desired behavior is to return all maximum values.
Solution:
There is currently no direct way to achieve this behavior without explicitly collecting partial results in a collection. Here are two possible approaches:
Two-Pass Approach (Collection):
Collector-Based Approach (Single Pass):
Create a custom collector using the maxList method:
static <T> Collector<T, ?, List<T>> maxList(Comparator<? super T> comp) { // Implementation given in the reference answer }
Example:
Using the collector-based approach:
Stream<String> input = ... ; List<String> result = input.collect(maxList(comparing(String::length)));
This will return a list containing all strings with the maximum length in the input stream.
The above is the detailed content of How Can I Get All Maximum Values from a Java Stream?. For more information, please follow other related articles on the PHP Chinese website!