Saturday, 11 July 2015

Sorting in Descending order in Java.

We are using Collections.reverseOrder() method along with Collections.sort() in order to sort the list in decreasing order. In the below example we have used the following statement for sorting in reverse order.
Collections.sort(arraylist, Collections.reverseOrder());
However the reverse order sorting can also be done as following – This way the list will be sorted in ascending order first and then it will be reversed.
Collections.sort(list);
Collections.reverse(list);
Complete example:
package com.swain.sitansu;

import java.util.ArrayList;
import java.util.Collections;

public class ArraylistDesendingSort {

public static void main(String[] args) {

ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("AA");
arrayList.add("BB");
arrayList.add("ZZ");
arrayList.add("FF");

/* Unsorted list */
System.out.println("Before Sorting:");
for (String str : arrayList) {
System.out.println(str);
}

Collections.sort(arrayList, Collections.reverseOrder());

/* Sorted list with reverse order */
System.out.println("ArrayList in descending order:");
for (String str1 : arrayList) {

System.out.println(str1);
}

}
}

Output:

Before Sorting:
AA
BB
ZZ
FF
ArrayList in descending order:
ZZ
FF
BB
AA


No comments:

Post a Comment