How to Sort List in Java

Below is an example on how to sort list in java. In order to sort list in java, the object inside the list should implement Comparable interface and we will use Collections utility class in Java. Implementing the Comparable interface gives you the flexibility to write your own logic on how the sorting will be done.

Basically, return a negative integer if you want the passed object(argument) to be after the current(this) object in the list, return 0 if both objects are the equal, and return positive integer if you want the passed object to be added first in the list before this object. Much better if we take an example:

Assuming we have List of object A, and we want to sort the list based on the integer property of object A in ascending.

public class A implements Comparable<A> {
    private int code;

    public A(int code) {
        this.code = code;

    public int getCode() {
        return code;

    public int compareTo(A object) {
        if (this.code > object.getCode()) {
            return 1;
        } else if (this.code < object.getCode()) {
            return -1;
        } else {
            return 0;

Then, if we create objects of A and them to list, then use Collections.sort() method, the list will be sorted based on the implementation of Comparable interface.

public class SortList {

    public static void main(String[] args) {
        A a1 = new A(1);
        A a2 = new A(2);
        A a3 = new A(3);
        A a4 = new A(4);

        List<A> list = new ArrayList<A>();

        //sort the list
        for(A a: list) {

The output would be:

Share this tutorial!