Blog
Tutorials

Sorting Object Lists in Java

Learn how to sort object lists in Java using the Comparable interface and the Collections Framework.

SipPulse - Technical TeamMarch 1, 20132 min read
Share
Sorting Object Lists in Java

Sorting Object Lists in Java

Java provides elegant approaches to sorting through its Collections Framework — a robust API that includes advanced data structures such as ArrayList and LinkedList.

Basic example with Strings

The sort method from the Collections Framework significantly simplifies the sorting process:

List<String> lista = new ArrayList<String>();
lista.add("fogo");
lista.add("agua");
lista.add("vento");
lista.add("terra");

Collections.sort(lista);

for(String i : lista){
    System.out.println(i);
}
// Result: agua, fogo, terra, vento

The sort method determines ordering through the compareTo method of the Comparable interface, which returns zero for equal objects, negative for smaller objects, and positive for larger ones.

Sorting custom objects

For custom classes, implement the Comparable interface:

public class Carro implements Comparable<Carro> {
    private String cor;
    private int cilindrada;

    public Carro(String cor, int cilindrada) {
        this.cor = cor;
        this.cilindrada = cilindrada;
    }

    public int compareTo(Carro carro) {
        if(this.cilindrada > carro.cilindrada) return -1;
        else if(this.cilindrada < carro.cilindrada) return 1;
        return this.getCor().compareToIgnoreCase(carro.getCor());
    }
    // getters and setters...
}

This logic sorts by engine displacement in descending order and then by color alphabetically for equal displacements.

Built-in Classes with Comparable

Many Java classes already implement Comparable: String, BigDecimal, BigInteger, Byte, Character, Date, Double, Float, Integer, Long, Short, and URI. These can be sorted directly using Collections.sort().

#Java#programming#Collections

Related Articles