Using Collections.sort and Comparator in Java
Sorting a collection in Java is easy, just use Collections.sort(Collection) to sort your values. For example:
package de.vogella.algorithms.sort.standardjava;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Simple {
public static void main(String[] args) {
List list = new ArrayList();
list.add(5);
list.add(4);
list.add(3);
list.add(7);
list.add(2);
list.add(1);
Collections.sort(list);
for (Integer integer : list) {
System.out.println(integer);
}
}
}
This is possible because Integer implements the Comparable interface. This interface defines the method compare which performs pairwise comparison of the elements and returns -1 if the element is smaller then the compared element, 0 if it is equal and 1 if it is larger.
But what if what to sort differently, e.g. for example in different order. Well, you could just use Collection.reverse(). Or you define your own class with implements the interface Comparator.
package de.vogella.algorithms.sort.standardjava;
import java.util.Comparator;
public class MyIntComparable implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
}
}
package de.vogella.algorithms.sort.standardjava;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Simple2 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(4);
list.add(3);
list.add(7);
list.add(2);
list.add(1);
Collections.sort(list, new MyIntComparable());
for (Integer integer : list) {
System.out.println(integer);
}
}
}
The nice thing about this approach is that you then sort any object by any attribute or even a combination of attributes. For example if you have objects of type Person with an attribute income and dataOfBirth you could define different implementations of Comparator and sort the objects according to your needs.
August 6th, 2009 at 4:28 pm
If you want to sort in reverse order you should always use Collections.reverseOrder(Comparator) instead of implementing your own comparator. It is really easy to make an error when writing one, better to rely on provided and well tested libraries.
Use Collections.sort(list, Collections.reverseOrder()) to sort a list of integers in a reverse order.
August 6th, 2009 at 4:42 pm
The Comparator is needed if you have an object which does not implement the Comparable interface. But thanks for the hint; in case you have an object which implements Comparable interface reverseOrder() looks easier.
May 26th, 2010 at 9:35 am
short but nice info