Sorting Java Collections

Java collections are most of the data structures that come with the language, they share the same basics methods thanks to the collection interface, one of the most common things you may want to do with a collection, besides adding and removing elements, is sorting them.

Let’s see an example with ArrayList

public class Sorting {

	private final static ArrayList numbers = new ArrayList();

	public static void main(String[] args) {



Sorting an ArrayList of integers is as easy as using “Collections.sort” since Java already knows how to sort numbers, but what if we wanted to sort an array of objects? How does Java know which object is worth more than other? Well we need to tell Java how to compare our objects implementing the Comparator interface

Here is an example:

private ArrayList
articles = new ArrayList(); articles.add(new Article("gel27", 200)); private void sortArticles() { Collections.sort(articles, new Comparator
() { @Override public int compare(Article art1, Article art2) { char a1 = art1.getArticleCode().charAt(0); char a2 = art2.getArticleCode().charAt(0); if (a1 > a2) { return 1; } else if (a1 == a2) { return 0; } else { return -1; } } }); }

We implement Comparator using an anonymous class and override the compare method, this method arguments are the two objects to be compared and returns an int, 1 if the first object is greater than the second, 0 if they are equal and -1 if the second object is greater than the first one, you can pick any field from your object to perform the comparison, in this case I’m using the first character of the article code so the result will be an alphabetical ordered array, you could also use the compareTo method if you want to use the whole string instead of just the first character.


, , , , , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: