Wednesday, July 23, 2014

Sorting java collection

Java uses the Merge sorting algorithm to sort collection. We can sort java collections using the java.util.Collections.sort() method. This method applies for List'collection type:
- List
- LinkedList

Natural Sorting:
List list = new ArrayList();
//add elements to the list
Collections.sort(list);


Sorting uses a Comparator
List<CustomObject> list = new ArrayList<CustomObject>();
Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
    public int compare(CustomObject c1, CustomObject c2) {
        return c2.getYourField() - c1.getYourField(); // use your logic    }
};

Collections.sort(list, comparator);

No comments:

Post a Comment