Sort collections in java

Usual problem: When you pass a java list to Collections.sort(List list), the elements are sorted according to their returned values retrieved by calling the objects compareTo() methods. Well, what to do if you suddenly want to sort the same list by another criteria? Then a comparator is your friend.  A comparator knows how to compare two objects in the list to sort, and is basically defined by:

List listToSort = new ArrayList();
Collections.sort(listToSort, new Comparator(); {
	public int compare(SomeObject o1, SomeObject o2) {
		return o1.getSomeStringProperty().compareTo(o2.getSomeStringProperty());
List list

Leave a comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.