Sorting an ArrayList in Java
Learn how to sort an ArrayList in Java with Collections.sort and Comparator, for both simple values and objects, in ascending or descending order.
You can download the project for this post by clicking HERE.
One of the most interesting things when working with data structures like “stacks”, “queues”, “lists”, etc. is sorting them. In the post “Sorting Arrays in Java (with their indexes)” we implemented an API that let us sort Arrays along with their indexes, which is a very important feature that no well-known API implements in a simple way.
In this post we are going to show how to sort an ArrayList, whether it is an ArrayList of atomic data or an ArrayList of objects.
To do this we will need to work with Java’s “Collections” class. We are not going to explain the features of this class; we will simply use it to sort ArrayLists. As usual on this site, let’s show this with an example:
We are going to have an ArrayList called “arrayListInt”, which is an array of integers, and we will give it the following values (if you don’t know the add method, check out the post “ArrayList in Java, with examples“):
private static ArrayList arrayListInt = new ArrayList<>();
// Guardo datos en el ArrayList
arrayListInt.add(3); arrayListInt.add(4);
arrayListInt.add(2); arrayListInt.add(6);
arrayListInt.add(5); arrayListInt.add(1);
arrayListInt.add(7);
If we print this ArrayList in the order in which we stored the elements, the first element will be the number ‘3’, the second the number ‘4’ and, following the order, the last one will be the number ‘7’.
To sort this ArrayList from lowest to highest, we are going to use the “sort” method of the Collections class:
Collections.sort(arrayListInt);
This method sorts the ArrayList from lowest to highest, and the output is the following (in the project you can download, you can see the methods that print the ArrayLists to the screen):
Posicion(1) = 1
Posicion(2) = 2
Posicion(3) = 3
Posicion(4) = 4
Posicion(5) = 5
Posicion(6) = 6
Posicion(7) = 7
To sort it from highest to lowest, we need to create an object of the Comparator class so that it compares the elements and puts them in reverse order. We do it like this:
Comparator<Integer> comparador = Collections.reverseOrder();
Collections.sort(arrayListInt, comparador);
Running this part of the program and printing the resulting ArrayList to the screen, we get the ArrayList sorted from highest to lowest:
Posicion(1) = 7
Posicion(2) = 6
Posicion(3) = 5
Posicion(4) = 4
Posicion(5) = 3
Posicion(6) = 2
Posicion(7) = 1
But what happens if we have an ArrayList of objects of a certain class and we want to sort that ArrayList by the value of a certain attribute? Well, there is a simple solution that we will show next, which consists of overriding a method of the Comparator class.
Let’s suppose we have a class “Persona” like this:
class Persona {
private String nombre;
private int edad;
public Persona() {
}
public Persona(String nombre, int edad) {
this.nombre = nombre;
this.edad = edad;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getEdad() {
return edad;
}
public void setEdad(int edad) {
this.edad = edad;
}
@Override
public String toString() {
return this.getNombre() + " - " + this.getEdad();
}
}
Let’s suppose we have an ArrayList called “personas” with the following objects of the Persona class:
private static ArrayList personas = new ArrayList<>();
................
................
personas.add(new Persona("Pepe", 28));
personas.add(new Persona("Juan", 32));
personas.add(new Persona("Paco", 40));
personas.add(new Persona("Susi", 24));
personas.add(new Persona("Lola", 20));
personas.add(new Persona("Jose", 28));
personas.add(new Persona("Dani", 24));
personas.add(new Persona("Sara", 36));
We want to sort this ArrayList by the age of the people (from youngest to oldest), so we need to override the “compare” method of the Comparator class and call the “sort” method of the Collections class. We do it like this:
Collections.sort(personas, new Comparator<Persona>() {
@Override
public int compare(Persona p1, Persona p2) {
return new Integer(p1.getEdad()).compareTo(new Integer(p2.getEdad()));
}
});
As we can see, what the “compare” method does is compare two given ages. In this case we are comparing two attributes of type “Integer”. If we want to do it with a String, Double, etc., we only have to change the data type. The output of this code is the following:
Posicion(1) = Lola - 20
Posicion(2) = Dani - 24
Posicion(3) = Susi - 24
Posicion(4) = Pepe - 28
Posicion(5) = Jose - 28
Posicion(6) = Juan - 32
Posicion(7) = Sara - 36
Posicion(8) = Paco - 40
If we now want to sort from oldest to youngest, we only have to change the “compare” method by reversing the comparison:
Collections.sort(personas, new Comparator<Persona>() {
@Override
public int compare(Persona p1, Persona p2) {
// Here is the trick: now we compare p2 with p1 and not the other way around as before
return new Integer(p2.getEdad()).compareTo(new Integer(p1.getEdad()));
}
});
As a result of this sorting we get the following:
Posicion(1) = Paco - 40
Posicion(2) = Sara - 36
Posicion(3) = Juan - 32
Posicion(4) = Pepe - 28
Posicion(5) = Jose - 28
Posicion(6) = Dani - 24
Posicion(7) = Susi - 24
Posicion(8) = Lola - 20
That is, in short, everything you need to sort an ArrayList, whether by an attribute of a series of objects or with atomic data (really they are objects that represent atomic data: Integer, Double, etc.). We haven’t gone into detail explaining the Comparator and Collections classes, since the goal of this post is simply to give a solution for sorting an ArrayList.
“Sorting an ArrayList in Java” by Ricardo Moya at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

You may also like
Sorting Arrays in Java (with Their Indices)
Learn how to sort Java arrays in ascending or descending order and get their indices after sorting, using the SortArray API with int, float, double and String.
ArrayList in Java, with Examples
Learn how to use ArrayList in Java: add, remove and iterate elements, store objects, and work with nested ArrayLists, with practical examples.

Leave a comment