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

  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

 

Case 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;

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 values

Narayan Murthy
Dinesh
Nandan Nilekeni
Ashok Arora
Shibulal
Kris Gopalakrishnan
Raghavan


After Sorting: Iterating ArrayList values

Ashok Arora
Dinesh
Kris Gopalakrishnan
Nandan Nilekeni
Narayan Murthy
Raghavan
Shibulal

 

Case 2: Natural ordering using Comparable interface

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;

public class Customer implements Comparable<Customer> {

	// member variables
	int customerId;
	String customerName;

	// 2-arg parameterized constructor
	public Customer(int customerId, String customerName) {
		super();
		this.customerId = customerId;
		this.customerName = customerName;
	}

	// override toString() method
	@Override
	public String toString() {
		return "Customer [customerId=" + customerId + ", customerName="
				+ customerName + "]";
	}

	// 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;

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

 

Case 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 constructor
  • Overriding toString() method
package in.bench.resources.java.collection;

public class Customer {

	// member variables
	int customerId;
	String customerName;

	// 2-arg parameterized constructor
	public Customer(int customerId, String customerName) {
		super();
		this.customerId = customerId;
		this.customerName = customerName;
	}

	// override toString() method
	@Override
	public String toString() {
		return "Customer [customerId=" + customerId + ", customerName="
				+ customerName + "]";
	}
}

 

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;

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 and customized sorting logic class
  • implementing comparator interface, to store objects inside ArrayList
  • sorting according to comparator (i.e.; reverse ordering of customer Id)
  • prints customer objects in descending order of customer Id

ArrayListCustomizedSortingOfObjectType.java

package in.bench.resources.java.collection;

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:

https://docs.oracle.com/javase/tutorial/collections/intro/
https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
https://docs.oracle.com/javase/7/docs/api/java/util/List.html
https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html

 

Happy Coding !!
Happy Learning !!