Home >Java >javaTutorial >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
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!