0

I was sorting with

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

Now, I need to sorting by Absolute Value like this answer: abs_number = (number < 0) ? -number : number; (Not using Math.abs(x) or Math.sqrt(Math.pow(x, 2)))

How implement a new java.util.Comparator or java.util.function.ToIntFunction in order by AbsoluteValue in reverse Order?

joseluisbz
  • 1,491
  • 1
  • 36
  • 58
  • 1
    Why not use `abs`? The straight-forward solution is `someList.sorted(Comparator.comparingInt(v -> Math.abs(v.getValue())).reversed());`, but if you insist on not using `abs`, then just use `someList.sorted(Comparator.comparingInt(v -> v.getValue() < 0? -v.getValue(): v.getValue())).reversed());` – Holger May 18 '20 at 08:45
  • 1
    The same method in implementation of abs in http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/Math.java and here https://github.com/frohoff/jdk8u-jdk/blob/master/src/share/classes/java/lang/Math.java –  May 18 '20 at 21:32

1 Answers1

0

Check this Question:

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

According to implementation of Math.abs(x) is the same code that you are requiring.

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

Alternatively

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