Java Array Sort Descending
Efficiently sort a Java array in descending order by combining Arrays.sort()
and Collections.reverseOrder()
for object types including Integer:
For primitive types such as int
, you can leverage streams:
Sorting with custom comparators
Custom conditions for sorting can be effortlessly achieved using a Comparator. Collections.reverseOrder(myComparator)
does the trick:
Sorting lists in a descending way
Lists can be sorted too, using the Collections.sort()
method in combination with Collections.reverseOrder()
:
This method bypasses the need for manual sorting, saving your effort.
Descending with two-dimensional primitive arrays
Two-dimensional primitive arrays need each row to be sorted in ascending order first, followed by reversing each row:
Traps and pitfalls to sidestep
Here are a few key things to remember:
- Box primitive arrays when using
Collections.reverseOrder()
. - In-place array reversal alleviates additional space complexity: so reverse like a pro!
- When implementing
reverseArrayInPlace
, maintain efficiency to avoid causing bottlenecks.
Advanced sorting scenarios
In complex scenarios, for instance, sorting objects per multiple criteria, make use of Comparator.comparing()
chained with .thenComparing()
:
With this, you're sorting your array primarily by one attribute and secondarily by another, all in descending order.
Was this article helpful?