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

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:


In this example we implement the Comparator interface using an anonymous class and override the compare method. The method arguments are the two objects to be compared and it 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.

Leave a Reply