Master java skills

Sorting ArrayList With Comparable

There are situations when we would like to sort the objects of a list or a set. This can be done using a utility method sort() of class Collections.

Syntax of Collections.sort() method

Collections.sort(list);       //here list is the object of type List.

Before using this method, we must understand the Comparable interface. The reason is that only those list can be sorted using Collections.sort() method whose objects implement Comparable interface. Comparable interface makes sure that the objects are comparable. And when they are comparable, they can be sorted. If they are not comparable, they cannot be sorted.

Comparable interface

Comparable interface is a part of java.lang package.

java.lang.Comparable

This interface has only one method.

public int compareTo(T o);

Any class that implements this interface must override this method. Let’s understand it by an example

package com.sks;

public class Cricketer implements Comparable<Cricketer> {

	private int id;
	private String name;
	
	public Cricketer(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	@Override
	public int compareTo(Cricketer cricketer) {
		return this.name.compareTo(cricketer.name);
	}
}

The above class Cricketer is Comparable type and thus its object can be sorted. Now let’s have a look at compareTo method. Here it returns int value. Let’s see the meaning of it

  1. It returns 0 if the object being compared is equal to this object (the object on which compareTo() method is called)
  2. It returns -1 if the object being compared is greater than this object
  3. It returns 1 if the object being compared is lesser this object

But if you see, we are simply calling compareTo method on name property of Cricketer class. name is String type property, and String class by default implements Comparable interface and has logic to sort Strings alphabetically. We are making use of its default logic and thus calling compareTo method on it.

Note -> Not only String class but all the Wrapper classes like Integer, Float, Double etc impement Comparable interface. Therefore, if we need to compare any property of these types, we can directly call compareTo method on them.

Sorting ArrayList of String objects

package com.sks;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayListSortingExample {

	public static void main(String[] args) {
		
		List<String> names = new ArrayList<String>();
		names.add("Vivekanand");
		names.add("Gautama");
		names.add("Vasudev");
		
		System.out.println("List before sorting : " + names);
		Collections.sort(names);
		System.out.println("List after sorting : " + names);
	}
}
Output :

List before sorting : [Vivekanand, Gautama, Vasudev]
List after sorting : [Gautama, Vasudev, Vivekanand]

Sorting ArrayList containing custom objects

Let’s create a class Cricketer and object of this class to a list and sort them based on their name. Meaning, cricketers will be sorted based on their names in alphabetical order.

We have to make sure that Cricketer class implements Comparable interface and override its compareTo() method.

package com.sks;

public class Cricketer implements Comparable<Cricketer> {

	private int id;
	private String name;
	
	public Cricketer(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	@Override
	public int compareTo(Cricketer cricketer) {
		return this.name.compareTo(cricketer.name);
	}

        @Override
	public String toString() {
		return "Cricketer [id=" + id + ", name=" + name + "]";
	}
}
package com.sks;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayListSortingExample {

	public static void main(String[] args) {
		
		List<Cricketer> cricketerList = new ArrayList<Cricketer>();
		
		Cricketer c1 = new Cricketer(1, "Sunil Gavaskar");
		Cricketer c2 = new Cricketer(2, "Viv Richards");
		Cricketer c3 = new Cricketer(3, "Ricky Ponting");
		Cricketer c4 = new Cricketer(4, "Sachin Tendulkar");
		
		cricketerList.add(c1);
		cricketerList.add(c2);
		cricketerList.add(c3);
		cricketerList.add(c4);
		
		System.out.println("List before sorting : " + cricketerList);
		Collections.sort(cricketerList);
		System.out.println("List after sorting : " + cricketerList);
	}
}
Output :
List before sorting : [Cricketer [id=1, name=Sunil Gavaskar], Cricketer [id=2, name=Viv Richards], Cricketer [id=3, name=Ricky Ponting], Cricketer [id=4, name=Saching Tendulkar]]

List after sorting : [Cricketer [id=3, name=Ricky Ponting], Cricketer [id=4, name=Sachin Tendulkar], Cricketer [id=1, name=Sunil Gavaskar], Cricketer [id=2, name=Viv Richards]]

Sorting LinkedList

Since LinkedList also implements List interface like ArrayList, sorting of LinkedList can also be done using Collections.sort() method.

How to sort ArrayList in reverse order

In order to sort an ArrayList in reverse order all we need to do is negate the result of compareTo() method. Below override of compareTo() method explains the same.

  1. By negating the result of compareTo method
@Override
public int compareTo(Cricketer cricketer) {
	return -1 * this.name.compareTo(cricketer.name);
}

2. Using Collections.reverseOrder() method

Collections.sort(arraylist, Collections.reverseOrder());
// here arraylist is a reference variable pointing to an ArrayList object