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.
For input collections, a two-pass approach can be employed:
This solution accommodates multiple maximum values but incurs the cost of iterating over the entire input twice.
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 } ); }
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.
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!