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

后端 未结 7 952
陌清茗
陌清茗 2020-11-22 09:47

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

7条回答
  •  故里飘歌
    2020-11-22 10:03

    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
    

提交回复
热议问题