流排序,反转绝对值基于,实现比较器或 ToIntFunction,Java 8
Stream Sorted, Reversed Absolute Value based on , implementing Comparator or ToIntFunction, Java 8
我用
排序
someList.sorted(Comparator.comparingInt(someClass::getValue).reversed())
现在,我需要像这个答案一样按绝对值排序:abs_number = (number < 0) ? -number : number;
(不使用 Math.abs(x)
或 Math.sqrt(Math.pow(x, 2))
)
如何实现一个新的 java.util.Comparator
或 java.util.function.ToIntFunction
按 AbsoluteValue 逆序排序?
检查这个 :
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())
我用
排序someList.sorted(Comparator.comparingInt(someClass::getValue).reversed())
现在,我需要像这个答案一样按绝对值排序:abs_number = (number < 0) ? -number : number;
(不使用 )Math.abs(x)
或 Math.sqrt(Math.pow(x, 2))
如何实现一个新的 java.util.Comparator
或 java.util.function.ToIntFunction
按 AbsoluteValue 逆序排序?
检查这个
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())