How to use Comparator to Sort List

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);
    }
}

image

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

2 thoughts on “How to use Comparator to Sort List”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.