Java Array Sort descending?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Sorting in descending order is easy for object arrays in Java, but primitive arrays need an extra step because comparators do not work directly with primitive types. The right implementation depends on whether you have Integer[], String[], or primitive arrays such as int[].
Sort Object Arrays with Arrays.sort and Collections.reverseOrder
For wrapper types and other objects, the standard library already has what you need.
This is the cleanest option for Integer[], Long[], String[], and any other object array that has a natural ordering or a comparator.
Primitive Arrays Need a Different Approach
You cannot pass Collections.reverseOrder() to Arrays.sort for int[] because primitives are not objects. A common solution is to sort ascending and then reverse manually.
This is efficient and avoids boxing every element into an Integer.
Use Streams When Readability Matters More Than Boxing Cost
If you prefer a more declarative style and the array is not performance-critical, you can box, sort with a reverse comparator, and convert back.
This is concise, but it allocates more objects than the in-place reverse approach.
Sort Custom Types by a Field
For arrays of custom objects, define the ordering explicitly.
That pattern is often better than relying on a natural ordering because it makes the sort rule obvious at the call site.
Choose the Method Based on the Data Type
If the data is already in a primitive array, the in-place reverse pattern is usually the best default. If the data is an object array, use a comparator. If the code is one-off analysis code and readability matters more than object allocation, streams are fine.
The important point is that there is no one universal descending sort call for every Java array shape.
Common Pitfalls
- Trying to use
Collections.reverseOrder()directly onint[]or other primitive arrays. - Boxing primitives into wrappers without noticing the extra allocation cost.
- Sorting ascending and forgetting the manual reverse step for primitive arrays.
- Hiding the real sort rule when working with custom objects that need field-based ordering.
- Choosing a clever stream solution in hot code paths where simple in-place reversal is cheaper and clearer.
Summary
- Use
Arrays.sort(array, Collections.reverseOrder())for object arrays. - For primitive arrays, sort ascending and reverse in place.
- Streams can produce descending primitive arrays, but they add boxing overhead.
- Use explicit comparators for arrays of custom objects.
- Pick the approach that matches the data type and performance needs.

