Sorting list


During the development of applications it is often needed, to sort list of complex objects. Locale language peculiarities and special characters must also be regarded.

Sort Object

First a compare method will be integrated in the object, which should be sorted. This method will be later called during the real sorting proccess to compare two objects. The calling class takes the result to give the objects a higher or lower index in a list.

The Sort-Object must implement the Interface Comparable. In the definied methode compareTo, which must be integrated in the Sort-Object, any individual comparison of two objects can be done.

public class MyObject implements Comparable<MyObject> { public int compareTo(MyObject compareObject) { if (getNumber() < compareObject.getNumber()) return -1; else if (getNumber() == compareObject.getNumber()) return 0; else return 1; } }
Negative Integer:
Current Object is smaller than Compare Object
Current Object is equal Compare Object
Positive Integer:
Current Object is greater than Compare Object

Special Comparison

For special sorting of objects the class Collator will be used, which can be individual configured for comparison. Setting a sort strength causes for example the distinction between case-sensitive and case-insensitive. Furthermore local language peculiarities, like german umlauts, can be included in the sorting.

public int compareTo(MyObject compareObject) { collator = Collator.getInstance(Locale.GERMAN); collator.setStrength(Collator.SECONDARY); return, compareObject.getName()); }
Sorting with german language rules
Sorting strength causes a == A, a < ä


The real sorting of the list will be done with the class Collections. The methode sort can sort a list of objects, whereby the previous implemented methode compareTo is called to compare two objects.

List<MyObject> list = new ArrayList<MyObject>(); list.add(new MyObject("Jörg")); list.add(new MyObject("Mandy")); list.add(new MyObject("Jason")); Collections.sort(list);


The following classes demonstrate a german sorting based on firstname and lastname of the objects:

Johannes Hammoud Sorting list 25.02.2006

I Coding : Community about Java programing

Language German+-

Java JSF JavaScript HTML CSS NetBeans GlassFish MySQL