Explain Codes LogoExplain Codes Logo

Java Array Sort Descending

java
sorting
comparator
arrays
Alex KataevbyAlex Kataev·Oct 11, 2024
TLDR

Efficiently sort a Java array in descending order by combining Arrays.sort() and Collections.reverseOrder() for object types including Integer:

Integer[] array = {3, 1, 4, 5, 2}; Arrays.sort(array, Collections.reverseOrder()); // Result: [5, 4, 3, 2, 1]

For primitive types such as int, you can leverage streams:

int[] array = {3, 1, 4, 5, 2}; int[] descSorted = Arrays.stream(array) .boxed() .sorted(Collections.reverseOrder()) .mapToInt(Integer::intValue) .toArray(); // Voila! [5, 4, 3, 2, 1]

Sorting with custom comparators

Custom conditions for sorting can be effortlessly achieved using a Comparator. Collections.reverseOrder(myComparator) does the trick:

Comparator<CustomObject> myComparator = Comparator.comparing(CustomObject::getAttributeName).reversed(); Arrays.sort(customObjectArray, myComparator); // Congrats! Your array is sorted in descending order

Sorting lists in a descending way

Lists can be sorted too, using the Collections.sort() method in combination with Collections.reverseOrder():

List<Integer> list = Arrays.asList(3, 1, 4, 5, 2); Collections.sort(list, Collections.reverseOrder()); // Result: [5, 4, 3, 2, 1]

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:

int[][] multiArray = {{3, 5}, {1, 4}}; for (int[] row : multiArray) { Arrays.sort(row); reverseArrayInPlace(row); // Reverse sort, because why not? }

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():

Arrays.sort(objectsArray, Comparator.comparing(ObjectType::getPrimaryAttribute) .thenComparing(ObjectType::getSecondaryAttribute) .reversed());

With this, you're sorting your array primarily by one attribute and secondarily by another, all in descending order.