我有
Map<String,LongAdder>
我想按流中的最佳方式对值进行排序。这比使用 Long 更难,因为 LongAdder 没有实现 Comparable,所以我必须使用 longValue(如果使用减法来制作比较器,则必须使用 intValue)。
我知道我可以用
m.entrySet().stream().sorted((a, b) -> b.getValue().intValue() - a.getValue().intValue())
但实际上我还想对键 (String) 进行二次排序。我也在颠倒排序。
我想做
m.entrySet().stream().sorted(
Comparator.comparing((a, b) -> b.getValue().intValue() - a.getValue().intValue()))
这样我可以在之后使用 thenComparing() 链接更多的比较器
异常(exception)情况是
Lambda expression's signature does not match the signature of the functional interface method apply(T)
但即使声明一个独立的比较器也不起作用:
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.comparingLong
是你需要的:
Comparator<Map.Entry<String, LongAdder>> byCount =
Comparator.comparingLong((Map.Entry<String, LongAdder> e) ->
e.getValue().longValue()).reversed().thenComparing(...);
重要说明:不要忘记使用显式类型化的 lambda 表达式,否则像 comparing(...).thenComparing(...)
这样的方法链在这种特殊情况下将无法编译1.
1 - 这 answer解释原因。
关于java - 在流中对 LongAdder 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56633140/