Possible Duplicate:
Sort arrays of primitive types in descending order
Java : How to sort an array of floats in reverse order?
How do I reverse an int array in Java?
The following code will sort the array in ascending order :
int a[] = {30,7,9,20};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
I need to sort it in descending order. How do I use Comparator to do this?
Please help.
Guava has a method Ints.asList()
for creating a List<Integer>
backed by an int[]
array. You can use this with Collections.sort to apply the Comparator to the underlying array.
List<Integer> integersList = Ints.asList(arr);
Collections.sort(integersList, Collections.reverseOrder());
Note that the latter is a live list backed by the actual array, so it should be pretty efficient.
If it's not a big/long array just mirror it:
for( int i = 0; i < arr.length/2; ++i )
{
temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
// option 1
Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
Arrays.sort(array, comparator);
// option 2
int[] array2 = new int[] { 1, 24, 4, 4, 345 };
List<Integer>list = Ints.asList(array2);
Collections.sort(list, comparator);
array2 = Ints.toArray(list);
Source: Stackoverflow.com