Home >Java >javaTutorial >How to Return All Maximum Values from a Java Stream Using the `max` Function?

How to Return All Maximum Values from a Java Stream Using the `max` Function?

Linda Hamilton
Linda HamiltonOriginal
2024-12-13 12:24:11889browse

How to Return All Maximum Values from a Java Stream Using the `max` Function?

Return All Maximum Values Using Max Function in Java Streams

When utilizing the max function in Java 8's lambda streams, discrepancies can emerge in scenarios where multiple objects yield the same maximum value. The function outputs an arbitrary representative without evaluating or considering all viable candidates.

To address this limitation, an alternative method is necessary to retrieve all maximum values accurately. Unfortunately, a straightforward approach is unavailable, requiring the utilization of a collection to hold partial results.

Two-Pass Solution

For input stored in a collection (List list), a two-stage process can be employed:

  1. Ascertain the length of the longest string (e.g., int longest = list.stream().mapToInt(String::length).max().orElse(-1);).
  2. Filter the list to extract all strings with the maximum length (e.g., List result = list.stream().filter(s -> s.length() == longest).collect(toList());).

Single-Pass Solution (Streams)

To tackle the single-pass scenario with streams, a custom collector can be constructed based on the provided Comparator:

static <T> Collector<T, ?, List<T>> maxList(Comparator<? super T> comp) {
    return Collector.of(
        ArrayList::new,
        (list, t) -> {
            int c;
            if (list.isEmpty() || (c = comp.compare(t, list.get(0))) == 0) {
                list.add(t);
            } else if (c > 0) {
                list.clear();
                list.add(t);
            }
        },
        (list1, list2) -> {
            // Processing for list merging logic
        }
    );
}

To utilize this collector in a stream, simply invoke collect:

Stream<String> input = ... ;
List<String> result = input.collect(maxList(comparing(String::length)));

The above is the detailed content of How to Return All Maximum Values from a Java Stream Using the `max` Function?. 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