Java Comparable Interface

Java Comparable interface is part of Collection Framework. Learn the purpose of Comparable interface and use it in different scenarios.

1. Comparable Interface

1.1. Why Implement Comparable?

In Java, if we want to sort a List of elements then we can Collections.sort() method. It sorts the list items according to the natural ordering. All Java wrapper classes, date-time classes and String etc. implement Comparable interface and so they have their natural order defined.

For example, java.lang.String class has lexicographical order (or dictionary order) as its natural order. So if we sort a list of String objects, they will be sorted as they will appear in a dictionary. Similarly, Integer objects will be sorted in ascending order, naturally.

But we need to define the natural ordering of the custom domain classes that we create in the application. For example, Employee, Order etc. This is required if we want to sort a list of employees or orders using the Collections.sort() method or any such method that expects the list items to be Comparable.

So, the primary purpose of Comparable interface is to define the natural sort order of the classes that implement it.

1.2. Implementing Comparable

Comparable interface has a single abstract method compareTo() that objects need to implement to have a natural ordering.

  • The objects must be mutually comparable and must not throw ClassCastException for any key in the collection.
  • The compareTo() method 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 compareTo() must throw an exception if y.compareTo(x) throws an exception.
  • Also, the relationship between the comparable objects must be transitive i.e. (x.compareTo(y) > 0 && y.compareTo(z) > 0) implies x.compareTo(z)>0.
  • null is not an instance of any class so e.compareTo(null) should throw a NullPointerException.
public interface Comparable<T> 
{
    public int compareTo(T o);
}

For example, for Employee class, the natural ordering can be based on the id field.

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() );
    }
}

Using Comparable interface, we can sort all types of objects including strings, wrapper classes or custom objects.

See Also: Sorting with Comparable and Comparator

2. Using Comparable

We can use sort the objects, that implement Comparable interface, using the following ways:

2.1. Collections.sort() and Arrays.sort()

Collections.sort(items);  
Arrays.sort(items); 

2.2. Collections.reverseOrder()

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

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

Collections.sort(items, Collections.reverseOrder());    
Arrays.sort(items, Collections.reverseOrder()); 

2.3. Sorted Collections

Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set (e.g. TreeSet), without the need to specify a comparator.

//All all items are automatically sorted
SortedSet<Item> itemsSet = new TreeSet<>();

2.4. Streams

Stream.sorted() can be used to sort a stream of objects that implement Comparable interface. However, note that a stream.sorted() does not sort the original collection – only the items in the stream are sorted.

items.stream()
	.sorted()
	.forEach(i -> System.out.println(i); 

3. Comparable Examples

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

3.1. Sorting 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]

3.2. Sort Strings in Reverse Order

Java program to sort a list of strings in reverse order 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]

3.3. Sorting Integers

Java program to sort a list of integers, on natural order and reverse order, 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]

3.4. Sort List of Custom Objects

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]
]

4. Conclusion

In this tutorial, we learned about Comparable interface. This interface helps in imposing a natural order on objects with simple interface implementation. We also learned to sort a list of strings, array of strings, list of integers, and array of integers. We learned how to sort Employee objects in Java using Comparable.

Refer to Guide to Sorting in Java for more information.

Happy Learning !!

Leave a Reply

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial