Java – Sorting ArrayList using Comparable and Comparator

In this article, we will discuss how to sort elements of List using Collections class’s utility sort() method

Sorting ArrayList using Comparable/Comparator interfaces:

  1. Default natural sorting order for String, Wrapper types
  2. java.lang.Comparable interface –> for natural ordering of Objects
  3. java.util.Comparator interface –> for customized sorting of Objects

Cautions:

  1. Objects should be of Comparable type like String or Wrapper class or else override compareTo() method, otherwise ClassCastException will be thrown
  2. Specified list to the sort() method shouldn’t contain any NULL value, otherwise NullPointerException will be thrown

1. Natural ordering of String type

  • Method signature : public static void sort(List<String> strList)
  • String and wrapper classes already implements comparable interface, so when we store elements of String type then we can use Collections sort() method to sort elements in ascending order of alphabets
  • Note: there shouldn’t be any NULL elements, otherwise NullPointerException will be thrown

ArrayListNaturalSortingOfStringType.java

package in.bench.resources.java.collection.sorting.arraylist;

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

public class ArrayListNaturalSortingOfStringType {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> al = new ArrayList<String>();


		// adding elements to ArrayList object
		al.add("Narayan Murthy");
		al.add("Dinesh");
		al.add("Nandan Nilekeni");
		al.add("Ashok Arora");
		al.add("Shibulal");
		al.add("Kris Gopalakrishnan");
		al.add("Raghavan");


		System.out.println("Before Sorting:"
				+ " Iterating ArrayList\n");


		// Iterating using enhanced for-loop
		for(String str : al){
			System.out.println(str);
		}


		// sorting using Collections.sort(al);
		Collections.sort(al);


		System.out.println("\n\nAfter Sorting:"
				+ " Iterating ArrayList\n");


		// Iterating using enhanced for-loop
		for(String str : al){
			System.out.println(str);
		}
	}
}

Output:

Before Sorting: Iterating ArrayList

Narayan Murthy
Dinesh
Nandan Nilekeni
Ashok Arora
Shibulal
Kris Gopalakrishnan
Raghavan


After Sorting: Iterating ArrayList

Ashok Arora
Dinesh
Kris Gopalakrishnan
Nandan Nilekeni
Narayan Murthy
Raghavan
Shibulal

2. Comparable interface and Collections.sort() method

  • Method signature: public static void sort(List<Object> list);

Customer.java

  • Customer POJO with 2 member variables of Integer and String type
  • which implements Comparable interface to provide natural ordering of Customer objects on the basis of customer name
package in.bench.resources.java.collection.sorting.arraylist;

public class Customer implements Comparable<Customer> {

	// member variables
	int customerId;
	String customerName;

	// 2-arg parameterized constructor

	// override toString() method

	// override compareTo() method
	@Override
	public int compareTo(Customer o) {
		return this.customerName.compareTo(o.customerName);
	}
}

Main class

  • This class uses above customer POJO to store objects inside ArrayList and
  • prints customer objects in ascending order of customer name

ArrayListNaturalSortingOfObjectType.java

package in.bench.resources.java.collection.sorting.arraylist;

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

public class ArrayListNaturalSortingOfObjectType {

	public static void main(String[] args) {

		// creating ArrayList object of type Customer
		ArrayList<Customer> al = new ArrayList<Customer>();


		// adding elements to TreeSet object
		al.add(new Customer(101, "Narayan Murthy"));
		al.add(new Customer(107, "Dinesh"));
		al.add(new Customer(103, "Nandan Nilekeni"));
		al.add(new Customer(102, "Ashok Arora"));
		al.add(new Customer(104, "Shibulal"));
		al.add(new Customer(106, "Kris Gopalakrishnan"));
		al.add(new Customer(105, "Raghavan"));


		System.out.println("Before Sorting:"
				+ " Insertion Order\n");


		// insertion order
		for(Customer cust : al){
			System.out.println(cust.customerId + "  "
					+ cust.customerName);
		}


		// sorting using Collections.sort(al);
		Collections.sort(al);


		System.out.println("\n\nAfter Sorting:"
				+ " Natural ordering of Customer Name\n");


		// natural ordering of customer name using Comparable
		for(Customer cust : al){
			System.out.println(cust.customerId + "  "
					+ cust.customerName);
		}
	}
}

Output:

Before Sorting: Insertion Order

101  Narayan Murthy
107  Dinesh
103  Nandan Nilekeni
102  Ashok Arora
104  Shibulal
106  Kris Gopalakrishnan
105  Raghavan


After Sorting: Natural ordering of Customer Name

102  Ashok Arora
107  Dinesh
106  Kris Gopalakrishnan
103  Nandan Nilekeni
101  Narayan Murthy
105  Raghavan
104  Shibulal

3. Customized Sorting using Comparator interface

Method signature: public static void sort(List<Object> list, Comparator<Object> c)

Customer.java

  • Customer POJO with 2 member variables of Integer and String type
  • 2-arg parameterized constructor
  • Overriding toString() method
package in.bench.resources.java.collection.sorting.arraylist;

public class Customer implements Comparable<Customer> {

	// member variables
	int customerId;
	String customerName;

	// 2-arg parameterized constructor

	// override toString() method
}

CustomerIdComparator.java

  • This is separate class which implements Comparator interface providing customized sorting logic
  • compare(); method provides reverse order sorting logic, according to customer Id
package in.bench.resources.java.collection.sorting.arraylist;

import java.util.Comparator;

public class CustomerIdComparator implements Comparator<Customer> {

	@Override
	public int compare(Customer o1, Customer o2) {
		return o2.customerId - o1.customerId;
	}
}

Main class

  • This class uses above customer POJO to store/save/add objects inside ArrayList
  • which implements comparator interface providing customized sorting logic class
  • i.e.; reverse ordering of customer Id
  • finally prints customer objects in descending order of customer Id

ArrayListCustomizedSortingOfObjectType.java

package in.bench.resources.java.collection.sorting.arraylist;

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

public class ArrayListCustomizedSortingOfObjectType {

	public static void main(String[] args) {

		// creating ArrayList object of type Customer
		ArrayList<Customer> al = new ArrayList<Customer>();


		// adding elements to TreeSet object
		al.add(new Customer(101, "Narayan Murthy"));
		al.add(new Customer(107, "Dinesh"));
		al.add(new Customer(103, "Nandan Nilekeni"));
		al.add(new Customer(102, "Ashok Arora"));
		al.add(new Customer(104, "Shibulal"));
		al.add(new Customer(106, "Kris Gopalakrishnan"));
		al.add(new Customer(105, "Raghavan"));


		System.out.println("Before Sorting:"
				+ " Insertion Order\n");


		// insertion order
		for(Customer cust : al){
			System.out.println(cust.customerId + "  "
					+ cust.customerName);
		}


		// sorting using Collections.sort(al, comparator);
		Collections.sort(al, new CustomerIdComparator());


		System.out.println("\n\nAfter Sorting:"
				+ " Reverse ordering of Customer Id\n");


		// reverse ordering of customer Id using Comparator
		for(Customer cust : al){
			System.out.println(cust.customerId + "  "
					+ cust.customerName);
		}
	}
}

Output:

Before Sorting: Insertion Order

101  Narayan Murthy
107  Dinesh
103  Nandan Nilekeni
102  Ashok Arora
104  Shibulal
106  Kris Gopalakrishnan
105  Raghavan


After Sorting: Reverse ordering of Customer Id

107  Dinesh
106  Kris Gopalakrishnan
105  Raghavan
104  Shibulal
103  Nandan Nilekeni
102  Ashok Arora
101  Narayan Murthy

References:

Happy Coding !!
Happy Learning !!

Java - Searching element from ArrayList using Binary Search Algorithm
Java - Collections a utility class for Collection