Search code examples
javacollectionslambdajava-8java-stream

How to force max to return ALL maximum values in a Java Stream?


I've tested a bit the max function on Java 8 lambdas and streams, and it seems that in case max is executed, even if more than one object compares to 0, it returns an arbitrary element within the tied candidates without further consideration.

Is there an evident trick or function for such a max expected behavior, so that all max values are returned? I don't see anything in the API but I am sure it must exist something better than comparing manually.

For instance:

// myComparator is an IntegerComparator
Stream.of(1, 3, 5, 3, 2, 3, 5)
    .max(myComparator)
    .forEach(System.out::println);
// Would print 5, 5 in any order.

Solution

  • I would group by value and store the values into a TreeMap in order to have my values sorted, then I would get the max value by getting the last entry as next:

    Stream.of(1, 3, 5, 3, 2, 3, 5)
        .collect(groupingBy(Function.identity(), TreeMap::new, toList()))
        .lastEntry()
        .getValue()
        .forEach(System.out::println);
    

    Output:

    5
    5