Home >Java >javaTutorial >How to Find All Maximum Values in a Java Stream?

How to Find All Maximum Values in a Java Stream?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 19:06:21429browse

How to Find All Maximum Values in a Java Stream?

How to Retrieve 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):

  • Find the maximum value using max and store it.
  • Filter the collection to include only elements that match the maximum value.
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):

  • Employ a custom collector that maintains a list of all elements with the current maximum value during stream processing.
  • Return the collected list as the result.
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn