Java 流中的长加法器排序
我有 但我实际上还想在键(字符串)上进行第二次排序。我也在扭转这种局面 我想做什么Java 流中的长加法器排序,java,sorting,java-stream,Java,Sorting,Java Stream,我有 但我实际上还想在键(字符串)上进行第二次排序。我也在扭转这种局面 我想做什么 m.entrySet().stream().sorted((a, b) -> b.getValue().intValue() - a.getValue().intValue()) 这样我就可以在后面用thenComparing()链接更多的比较器 例外是 m.entrySet().stream().sorted( Comparator.comparing((a, b) -> b.getValue()
m.entrySet().stream().sorted((a, b) -> b.getValue().intValue() - a.getValue().intValue())
这样我就可以在后面用thenComparing()链接更多的比较器
例外是
m.entrySet().stream().sorted(
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)
comparatorbycount=比较器。比较((a,b)->
(b.getValue().intValue()-a.getValue().intValue());
Lambda表达式的签名与函数接口方法apply(T)的签名不匹配
我不能使用函数引用“::“因为它有太多的部分:Map.Entry.getValue().intValue()。您的独立比较器可以固定为使用
函数,并且看起来像:
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)
comparatorbycount=Comparator.comparingit(e->e.getValue().intValue());
是您所需要的:
Comparator<Map.Entry<String,LongAdder>> byCount = Comparator.comparingInt(e -> e.getValue().intValue());
比较器byCount=
Comparator.comparingLong((Map.Entry e)->
e、 getValue().longValue()).reversed().Then比较(…);
重要提示:不要忘记使用显式类型的lambda表达式,否则方法链接(如比较(…)。在这种特殊情况下,比较(…)
将无法编译1
1-这解释了原因。
比较器。比较
不需要比较器-它需要一个从对象映射到可比较对象的函数。另外,永远不要使用减法进行比较-它可能会溢出并给出错误的结果。使用整数。比较。另外,如果您的数字实际上是长的,请不要使用intValue
,这同样会丢失信息。对于一个级别,您可以在使用Comparator byCount=Map.Entry.comparingByValue(Comparator.comparingLong(LongAdder::sum).reversed()时避免显式类型但是当链接另一个排序条件时,您最终需要显式类型,比如comparatorbycount2=Map.Entry.comparingByValue(Comparator.comparingLong(LongAdder::sum).reversed())。然后是comparing(…)代码>
Comparator<Map.Entry<String,LongAdder>> byCount = Comparator.comparingInt(e -> e.getValue().intValue());
Comparator<Map.Entry<String, LongAdder>> byCount =
Comparator.comparingLong((Map.Entry<String, LongAdder> e) ->
e.getValue().longValue()).reversed().thenComparing(...);