【发布时间】:2019-06-17 14:13:24
【问题描述】:
我有
Map<String,LongAdder>
我想按流中的最佳方式按值排序。这比使用 Long 更难,因为 LongAdder 没有实现 Comparable 所以我必须使用 longValue (或 intValue 如果使用减法来制作 Comparator)。
我知道我可以使用
m.entrySet().stream().sorted((a, b) -> b.getValue().intValue() - a.getValue().intValue())
但我实际上还想对键(字符串)进行第二次排序。我也在颠倒排序。
我想做
m.entrySet().stream().sorted(
Comparator.comparing((a, b) -> b.getValue().intValue() - a.getValue().intValue()))
这样我就可以使用 thenComparing() 链接更多的比较器
例外是
Lambda expression's signature does not match the signature of the functional interface method apply(T)
但即使声明一个独立的 Comparator 这也行不通:
Comparator<Map.Entry<String,LongAdder>> byCount = Comparator.comparing((a,b) ->
(b.getValue().intValue() - a.getValue().intValue()));
Lambda expression's signature does not match the signature of the functional interface method apply(T)
我不能使用函数引用“::”,因为它的部分太多:Map.Entry.getValue().intValue()。
【问题讨论】:
-
Comparator.comparing不需要Comparator- 它需要一个从您的对象映射到可比较对象的函数。此外,切勿使用减法进行比较 - 它可能会溢出并给您错误的结果。使用Integer.compare。此外,如果您的数字实际上很长,请不要使用intValue- 再次,您会丢失信息。
标签: java sorting java-stream