Home > Java > javaTutorial > How Can I Retrieve All Maximum Values from a Java Stream, Handling Ties Effectively?

How Can I Retrieve All Maximum Values from a Java Stream, Handling Ties Effectively?

Mary-Kate Olsen
Release: 2024-12-14 14:45:16
Original
499 people have browsed it

How Can I Retrieve All Maximum Values from a Java Stream, Handling Ties Effectively?

Overcoming Java Stream's Limitation in Returning All Max Values

Stream's max function conveniently identifies the maximum value within a stream. However, it operates on a "first-come, first-served" principle, potentially leaving out other maximum values if there are ties. To address this limitation and retrieve all maximum values, alternative approaches are necessary.

Two-Pass Solution

For input collections, a two-pass approach can be employed:

  1. Determine the maximum value using max on integer lengths.
  2. Filter the collection to obtain all strings with the maximum length.

This solution accommodates multiple maximum values but incurs the cost of iterating over the entire input twice.

Single-Pass Collector

When the input is a stream, a single-pass collector can be utilized:

static <T> Collector<T, ?, List<T>> maxList(Comparator<? super T> comp) {
    return Collector.of(
        ArrayList::new,
        (list, t) -> {
            if (list.isEmpty() || comp.compare(t, list.get(0)) == 0) {
                list.add(t);
            } else if (comp.compare(t, list.get(0)) > 0) {
                list.clear();
                list.add(t);
            }
        },
        (list1, list2) -> {
            ...
            // Compare and merge lists based on maximum values
        }
    );
}
Copy after login

This collector maintains the invariant of equivalence, adding or removing elements as necessary. When merging lists, it considers the maximum element of each and combines them when equal.

By combining this collector with the stream, all maximum values can be obtained in a single pass.

Conclusion

While max in Java streams has its limitations, alternative solutions can be leveraged to overcome them. A two-pass solution is efficient for collections, while the single-pass collector proves useful for streams, allowing for retrieval of all maximum values.

The above is the detailed content of How Can I Retrieve All Maximum Values from a Java Stream, Handling Ties Effectively?. 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