Sort primitive int array in reverse order in Java
How to sort primitive int array in reverse order
Arrays.sort()
can not be used directly to sort primitive arrays in descending order.
You have to use Integer[]
rather than int[]
.
Integer[] arr = new Integer[] {8, 4, 1, 7};
Arrays.sort(arr, Collections.reverseOrder());
If you still want to keep int[]
, there’s another way to approach it.
int[] nums = new int[] {8, 4, 1, 7};
int[] nums = IntStream.of(nums).boxed()
.sorted(Collections.reverseOrder())
.mapToInt(value -> value.intValue())
.toArray(); // [8, 7, 4, 1]
reference
Stack Overflow / How to sort an IntStream in reverse order
Stack Overflow / Java Array Sort descending?