且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何强制 max 返回 Java Stream 中的所有最大值?

更新时间:2022-06-20 22:37:01

我会按值分组并将值存储到 TreeMap 中以便对我的值进行排序,然后我会得到最大值通过获取最后一个条目作为下一个值:

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);

输出:

5
5