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
Release: 2024-12-13 12:24:11
Original
894 people have browsed it

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
        }
    );
}
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template