Java Comparable interface example

Java Comparable interface used to sort a array or list of objects based on their natural order. Natural ordering of elements is imposed by implementing it’s compareTo() method in the objects.

1. Java Comparable interface

public interface Comparable<T> 
{
	public int compareTo(T o);
}

Java Comparable interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class’s natural ordering, and the class’s compareTo() method is referred to as its natural comparison method.

Using Comparable interface, we can sort the elements of:

  1. String objects
  2. Wrapper class objects, for example Integer, Long etc
  3. User defined custom objects

1.1. compareTo() method

For any class to support natural ordering, it should implement the Comparable interface and override it’s compareTo() method. It must return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Note that method must throw an exception if y.compareTo(x) throws an exception. Also the relation must be transitive i.e. (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

For example, for Employee class, the natural ordering can be based on it’s employee id.

import java.time.LocalDate;

public class Employee implements Comparable<Employee> {

    private Long id;
    private String name;
    private LocalDate dob;
    
    @Override
    public int compareTo(Employee o) 
    {
        return this.getId().compareTo( o.getId() );
    }
}

All wrapper classes and String class implement Comparable interface. Wrapper classes are compared by their values, and strings are compared lexicographically.

1.2. Collections.sort() and Arrays.sort()

  1. Use Collections.sort() method sort a list of objects.
  2. Use Arrays.sort() method sort an array of objects.

1.3. Collections.reverseOrder()

This utility method returns a Comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

This enables a simple idiom for sorting (or maintaining) collections (or arrays) of objects that implement the Comparable interface in reverse-natural-order.

2. Java Comparable example

All given examples sort the lists using Collections.sort() method. If we need to sort the arrays of same objects, simply replace Collections.sort() with Arrays.sort().

2.1. Sort list of strings

Java program to sort a list of strings using Comparable interface.

ArrayList<String> list = new ArrayList<>();

list.add("E");
list.add("A");
list.add("C");
list.add("B");
list.add("D");

Collections.sort(list);

System.out.println(list);

Program Output.

[A, B, C, D, E]

2.2. Sort list of strings in reverse order

Java program to sort a list of strings using Comparable interface.

ArrayList<String> list = new ArrayList<>();

list.add("E");
list.add("A");
list.add("C");
list.add("B");
list.add("D");

//Sort in reverse natural order
Collections.sort(list, Collections.reverseOrder());

System.out.println(list);

Program Output.

[E, D, C, B, A]

2.3. Sort list of integers

Java program to sort a list of integers using Comparable interface.

ArrayList<Integer> list = new ArrayList<>();
        
list.add(10);
list.add(300);
list.add(45);
list.add(2);
list.add(5);

//Natural order
Collections.sort(list);

System.out.println(list);

//Sort in reverse natural order
Collections.sort(list, Collections.reverseOrder());

System.out.println(list);

Program Output.

[2, 5, 10, 45, 300]
[300, 45, 10, 5, 2]

2.4. Sort list of employees

Java program to sort a list of custom object using Comparable interface. In this example, we are sorting a list of employees by id.

ArrayList<Employee> list = new ArrayList<>();
        
list.add(new Employee(22l, "Lokesh", LocalDate.now()));
list.add(new Employee(18l, "Alex", LocalDate.now()));
list.add(new Employee(30l, "Bob", LocalDate.now()));
list.add(new Employee(600l, "Charles", LocalDate.now()));
list.add(new Employee(5l, "David", LocalDate.now()));

//Natural order
Collections.sort(list);

System.out.println(list);

//Sort in reverse natural order
Collections.sort(list, Collections.reverseOrder());

System.out.println(list);

Program Output.

[
	Employee [id=5, name=David, dob=2018-10-29], 
	Employee [id=18, name=Alex, dob=2018-10-29], 
	Employee [id=22, name=Lokesh, dob=2018-10-29], 
	Employee [id=30, name=Bob, dob=2018-10-29], 
	Employee [id=600, name=Charles, dob=2018-10-29]
]

//Reverse sorted

[
	Employee [id=600, name=Charles, dob=2018-10-30], 
	Employee [id=30, name=Bob, dob=2018-10-30], 
	Employee [id=22, name=Lokesh, dob=2018-10-30], 
	Employee [id=18, name=Alex, dob=2018-10-30], 
	Employee [id=5, name=David, dob=2018-10-30]
]

3. Conclusion

In this tutorial, we learned about Comparable interface of Java collection framework. It helps in imposing a natural order on objects with simple interface implementation.

We learned to sort list of strings, array of strings, list of integers, array of integers and we learned how to sort employee objects in java using comparable.

Drop me your questions in comments section.

Happy Learning !!

References:

Comparable Interface Java Docs

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.