Is there any EASY way to sort an array in descending order like how they have a sort in ascending order in the Arrays class?
Or do I have to stop being lazy and do this myself :[
Is there any EASY way to sort an array in descending order like how they have a sort in ascending order in the Arrays class? Or do I have to stop being lazy and do this myself :[ |
||||
|
You could use this
|
|||||||||||||
|
You can use this:
|
|||||||||||||
|
for a list
for an array
|
|||||||||||||||||
|
without explicit comparator:
with explicit comparator:
|
||||
|
an alternative could be (for numbers!!!)
Literally spoken:
|
|||||||||||||||||||||
|
I don't know what your use case was, however in addition to other answers here another (lazy) option is to still sort in ascending order as you indicate but then iterate in reverse order instead. |
|||
|
Another solution is that if you're making use of the Comparable interface you can switch the output values which you had specified in your compareTo(Object bCompared). For Example :
Where magnitude is an attribute with datatype double in my program. This was sorting my defined class freq in reverse order by it's magnitude. So in order to correct that, you switch the values returned by the
To make use of this compareTo, we simply call The beauty (in my opinion) of this solution is that it can be used to sort user defined classes, and even more than that sort them by a specific attribute. If implementation of a Comparable interface sounds daunting to you, I'd encourage you not to think that way, it actually isn't. This link on how to implement comparable made things much easier for me. Hoping persons can make use of this solution, and that your joy will even be comparable to mine. |
|||
|
For array which contains elements of primitives if there is
|
|||||||||||||||||
|
Java 8:
Update: It reverses the specified comparator. Usually comparators oder ascending, so this let's it order descending. |
|||||
|
First you need to sort your array using:
Then you need to reverse the order from ascending to descending using:
|
|||
|