How do we sort in Java?

  • We can go the traditional way by implementing Bubble Sort or Merge Sort etc
  • We can use Java APIs

In this post, we will focus on Sorting using Java APIs

Sort List of Integer

Given an Integer List say [7, 4, 2, 9, 5, 2, 3] to sort
We will use the Java Collection Framework to do this.

Points to Note:

  • List<Integer> => The Integer class wraps a value of the primitive type int in an object.
  • Collections.sort(ints) =>
    It sorts elements in order induced by the specified Comparator or else in element’s natural ordering. Sort technique used by Collections is mergesort.

Sort List of Object

  • Let’s create a list of Users and sort them by there Name (type String).
  • The user class will have two fields userName and phone number.
  • In order to be able to use the sort method from the collections class, we have to implement the comparable interface.


public class UserName implements Comparable<UserName>{
private String userName;
private String phoneNo;

// getter setters

The compiler shows an Error “The type UserName must implement the inherited abstract method Comparable<UserName>.compareTo(UserName)

This means that in order to implement Comparable we have to implement compareTo method of Comparable interface which goes like this:

public int compareTo(UserName u) {
int lastCmp = userName.compareTo(u.getUserName());
return (lastCmp != 0 ? lastCmp : userName.compareTo(u.getUserName()));

By implementing compareTo we are defining the element by which User Object must be sorted in element’s natural ordering and it can only be one. This method returns an int

  • 0: if objects are equal
  • -1: if less than
  • 1: if greater than


public static void main(String[] args) {

User name[] = {
new User("Aashish", 12),
new User("Suman", 12),
new User("Naveen", 34),
new User("Ashish", 10),
new User("Dheepan", 10),
new User("Satish", 26)

// Sort by natural order
List names = Arrays.asList(name);

// Sort by reverse natural order
Collections.sort(names, Collections.reverseOrder());
System.out.println("Sort by reverse natural order");


[Aashish 12, Ashish 10, Dheepan 10, Naveen 34, Satish 26, Suman 12]
Sort by reverse natural order
[Suman 12, Satish 26, Naveen 34, Dheepan 10, Ashish 10, Aashish 12]

Note : Collections.reverseOrder() => lets you sort in reverse natural order

When to use Comparable:

  • When we need to sort collection on the basis of a single element
Categories: JAVA


Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *