【问题标题】:Sorting LongAdder in streams对流中的 LongAdder 进行排序
【发布时间】: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


【解决方案1】:

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 解释了原因。

【讨论】:

  • 对于一个级别,您可以在使用 Comparator&lt;Map.Entry&lt;String, LongAdder&gt;&gt; byCount = Map.Entry.comparingByValue(Comparator.comparingLong(LongAdder::sum).reversed( )); 时避免显式类型但是当链接另一个排序条件时,您最终需要显式类型,例如 Comparator&lt;Map.Entry &lt;String, LongAdder&gt;&gt; byCount2 = Map.Entry.&lt;String, LongAdder&gt;comparingByValue(Comparator. comparingLong(LongAdder::sum).reversed()).thenComparing(…);
【解决方案2】:

您的独立比较器可以固定为使用Function,看起来像:

Comparator<Map.Entry<String,LongAdder>> byCount = Comparator.comparingInt(e -> e.getValue().intValue());

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 2021-02-22
    • 2018-11-11
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多