Home > Java > javaTutorial > How to Get All Maximum Values from a Java Stream?

How to Get All Maximum Values from a Java Stream?

Linda Hamilton
Release: 2024-12-08 13:33:11
Original
601 people have browsed it

How to Get All Maximum Values from a Java Stream?

How to Return Multiple Maximum Values in a Java Stream

In Java Stream API, the max function typically returns one of the maximum elements from a collection when provided with a comparator. However, what if we desire all maximum values, especially when several elements have the same maximum value?

Trick for Returning All Maximum Values

Unfortunately, the Java API does not provide a direct way to retrieve all maximum values. However, a workaround involves storing partial results using a Collector. Here's a helper function that generates a Collector based on a 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) -> {
            if (list1.isEmpty()) {
                return list2;
            } 
            if (list2.isEmpty()) {
                return list1;
            }
            int r = comp.compare(list1.get(0), list2.get(0));
            if (r < 0) {
                return list2;
            } else if (r > 0) {
                return list1;
            } else {
                list1.addAll(list2);
                return list1;
            }
        });
}
Copy after login

This Collector maintains a list of elements that are equivalent in terms of the Comparator. When merging results, the Collector returns the list with the greater elements. If the elements are equal, it appends the lists.

To use this Collector on a Stream, simply apply it as follows:

Stream<String> input = ... ;

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

Example Usage

For instance, let's find all strings with the maximum length in a list.

List<String> strings = Arrays.asList("apple", "banana", "pear", "orange", "grapes", "kiwi");

Stream<String> stringStream = strings.stream();

List<String> maxStrings = stringStream.collect(maxList(Comparator.comparingInt(String::length)));

System.out.println(maxStrings); // [apple, banana, grapes, orange]
Copy after login

In this example, the maxList Collector will return a list containing all strings that have the maximum length.

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