Home >Java >javaTutorial >How to Find All Maximum Values in a Java Stream?
In Java 8, the max function can be used on lambda and streams to identify the maximum value in a dataset. However, when multiple elements have the same maximum value, max arbitrarily chooses and returns one of them.
Expected Behavior:
The goal is to retrieve a list of all elements that share the maximum value, not just a single representative.
Solution:
Since the API lacks an explicit method for this functionality, you can implement a custom solution using intermediate storage and collection manipulation. Here are two approaches:
1. Two-Pass Solution (For Collections):
List<String> list = ... ; int longest = list.stream() .mapToInt(String::length) .max() .orElse(-1); List<String> result = list.stream() .filter(s -> s.length() == longest) .collect(toList());
2. Single-Pass Solution (For Streams):
static <T> Collector<T, ?, List<T>> maxList(Comparator<? super T> comp) { // Implementation goes here (provided in the original response) } Stream<String> input = ... ; List<String> result = input.collect(maxList(comparing(String::length)));
This custom collector tracks intermediate results and updates its state based on each element's value compared to the current maximum. By leveraging this approach, you can obtain a list containing all maximum values from your stream or collection.
The above is the detailed content of How to Find All Maximum Values in a Java Stream?. For more information, please follow other related articles on the PHP Chinese website!