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

How Can I Get All Maximum Values from a Java Stream?

Patricia Arquette
Release: 2024-12-08 12:37:12
Original
572 people have browsed it

How Can I Get All Maximum Values from a Java Stream?

Maximizing All Values in a Java Stream

Problem:
Java's max function in lambda expressions and streams typically returns an arbitrary element when multiple candidates tie for the maximum value. This can be undesirable when the desired behavior is to return all maximum values.

Solution:

There is currently no direct way to achieve this behavior without explicitly collecting partial results in a collection. Here are two possible approaches:

Two-Pass Approach (Collection):

  1. Determine the maximum value using mapToInt(String::length).max().
  2. Filter the input stream to obtain all elements that match the maximum length.

Collector-Based Approach (Single Pass):

  1. Create a custom collector using the maxList method:

    static <T> Collector<T, ?, List<T>> maxList(Comparator<? super T> comp) {
     // Implementation given in the reference answer
    }
    Copy after login
  2. Use the collector to gather all elements with the maximum value in a single pass.

Example:

Using the collector-based approach:

Stream<String> input = ... ;

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

This will return a list containing all strings with the maximum length in the input stream.

The above is the detailed content of How Can I 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