【问题标题】:Stream Sorted, Reversed Absolute Value based on , implementing Comparator or ToIntFunction, Java 8基于实现 Comparator 或 ToIntFunction、Java 8 的流排序、反转绝对值
【发布时间】:2020-05-17 19:10:01
【问题描述】:

我用

排序
someList.sorted(Comparator.comparingInt(someClass::getValue).reversed())

现在,我需要像这个答案一样按绝对值排序:abs_number = (number < 0) ? -number : number;(不使用 Math.abs(x)Math.sqrt(Math.pow(x, 2))

如何实现一个新的java.util.Comparatorjava.util.function.ToIntFunction,按AbsoluteValue倒序排列?

【问题讨论】:

标签: sorting java-8 java-stream comparator


【解决方案1】:

查看Question

someList
.sorted((a, b) -> 
    Integer.valueOf(b.getValue() < 0 ? -b.getValue() : b.getValue())
    .compareTo(a.getValue() < 0 ? -a.getValue() : a.getValue())
)

根据Math.abs(x) 中的implementation 是您需要的相同代码。

someList
.sorted((a, b) ->
    Integer.valueOf(Math.abs(b.getValue()))
    .compareTo(Math.abs(a.getValue()))
)

或者

someList
.sorted(Comparator.<SomeClass>comparingInt(s -> Math.abs(s.getValue())).reversed())

【讨论】:

    猜你喜欢
    • 2020-03-19
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 2019-05-17
    相关资源
    最近更新 更多