This tutorial demonstrated how to use comparator to sort Collection, for this example the ArrayList of List.
Now, I used the java.util.Collections static utility method, Collections.sort() method to sort the List, how I sort the list? I first sort the list in alphabetically, and otherwise I am using a user-defined comparator to sort in reverse order. Here is my code:
import java.util.*;
public class SortSort {
public static void main(String args[]) {
List<String> name = new ArrayList<String>();
name.add("Mohan");
name.add("Ali");
name.add("Hao");
name.add("Some");
System.out.println("Before: " + name);
Collections.sort(name);
System.out.println("After Sort: " + name);
Collections.sort(name, new reverseOrder());
System.out.println("After Reverse Sort: " + name);
}
}
class reverseOrder implements Comparator<String> {
public int compare(String one, String two) {
return two.compareTo(one);
}
}