Java – Sorting list of objects on multiple fields using Comparator

In previous articles, we have discussed how to sort list of objects on the basis of single field using Comparable and Comparator interfaces

Read Java 8 – Sorting list of objects on multiple fields for sorting list of Objects on the basis of multiple field using Java 8 Comparator and Stream‘s sorted() method

1. Sorting lists of Objects on Single field/parameter :

Sorting ArrayList contents in both ascending/descending order on the basis of single field

2. Sorting list of Objects on Multiple field/parameters :

What if we have a requirement to sort ArrayList of objects in accordance with 2/3 fields like,

  • First, sort according to customer name
  • Second, sort according to customer city if names are same
  • Third sorting w.r.t customer age if name/city are same

2.1 Steps to sort ArrayList contents w.r.t 3 member variables of Customer class:

  • Define Customer class with 3 member variables namely customer name, city and age
  • Write a custom sorting logic to sort Customer member variables w.r.t 3 field/parameters as per sequence (Name –> City –> Age)
  • Main test class, where we are going to create ArrayList and inserts some 10+ entries of Customer objects
  • Finally printing Customer objects before & after custom sorting logic from main class

Customer.java

package in.bench.resources.customized.sorting.multiple.fields;

public class Customer {

	// member variables
	String custName;
	String custCity;
	Integer custAge;

	// getters & setters

	// 3-arg parameterized constructor

	// overriding toString() method
}

CustomerSortingComparator.java

package in.bench.resources.customized.sorting.multiple.fields;

import java.util.Comparator;

public class CustomerSortingComparator implements Comparator<Customer> {

	@Override
	public int compare(Customer cust1, Customer cust2) {

		// 1. name comparison in alphabetical-order
		int compareName = cust1.getCustName().compareTo(cust2.getCustName());

		// 2. city comparison in alphabetical-order
		int compareCity = cust1.getCustCity().compareTo(cust2.getCustCity());

		// 3. age comparison in ascending-order
		int compareAge = cust1.getCustAge().compareTo(cust2.getCustAge());


		// 3-level comparison using if-else block
		if(compareName == 0) {
			return ((compareCity == 0) ? compareAge : compareCity);
		}
		else {
			return compareName;
		}
	}
}

TestCustomerSorting.java

package in.bench.resources.customized.sorting.multiple.fields;

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

public class TestCustomerSorting {

	public static void main(String[] args) {

		// 1. create ArrayList reference to store customers
		List<Customer> listOfCustomers = new ArrayList<Customer>();


		// 1.1 create customer objects using constructor initialization
		Customer cust1 = new Customer("Shalini", "Chennai", 60);
		Customer cust2 = new Customer("Sneha", "Pune",  73);
		Customer cust3 = new Customer("Simran", "Bangalore", 37);
		Customer cust4 = new Customer("Trisha", "Hyderabad", 52);
		Customer cust5 = new Customer("Shalini", "Chennai", 70);
		Customer cust6 = new Customer("Abirami", "Bangalore", 48);
		Customer cust7 = new Customer("Trisha", "Mangalore", 45);
		Customer cust8 = new Customer("Sneha", "Pune", 62);
		Customer cust9 = new Customer("Shalini", "Chennai",  50);


		// 1.2 add customer objects to ArrayList
		listOfCustomers.add(cust1);
		listOfCustomers.add(cust2);
		listOfCustomers.add(cust3);
		listOfCustomers.add(cust4);
		listOfCustomers.add(cust5);
		listOfCustomers.add(cust6);
		listOfCustomers.add(cust7);
		listOfCustomers.add(cust8);
		listOfCustomers.add(cust9);


		// 1.4 before Sorting: iterate using Iterator and while-loop
		Iterator<Customer> custIterator =
				listOfCustomers.iterator();


		// 1.5 print to console
		System.out.println("Before Sorting - Insertion-order of List :-\n");
		while(custIterator.hasNext()) {
			System.out.println(custIterator.next());
		}



		// 2. sorting using Collections.sort()
		Collections.sort(listOfCustomers, new CustomerSortingComparator());


		// 2.1 after Sorting: iterate using enhanced for-loop
		System.out.println("\n\nSorted order of Name -> City -> Age :-\n");
		for(Customer customer : listOfCustomers) {
			System.out.println(customer);
		}
	}
}

Output:

Before Sorting - Insertion-order of List :-

Customer [custName=Shalini, custCity=Chennai, custAge=60]
Customer [custName=Sneha, custCity=Pune, custAge=73]
Customer [custName=Simran, custCity=Bangalore, custAge=37]
Customer [custName=Trisha, custCity=Hyderabad, custAge=52]
Customer [custName=Shalini, custCity=Chennai, custAge=70]
Customer [custName=Abirami, custCity=Bangalore, custAge=48]
Customer [custName=Trisha, custCity=Mangalore, custAge=45]
Customer [custName=Sneha, custCity=Pune, custAge=62]
Customer [custName=Shalini, custCity=Chennai, custAge=50]


Sorted order of Name -> City -> Age :-

Customer [custName=Abirami, custCity=Bangalore, custAge=48]
Customer [custName=Shalini, custCity=Chennai, custAge=50]
Customer [custName=Shalini, custCity=Chennai, custAge=60]
Customer [custName=Shalini, custCity=Chennai, custAge=70]
Customer [custName=Simran, custCity=Bangalore, custAge=37]
Customer [custName=Sneha, custCity=Pune, custAge=62]
Customer [custName=Sneha, custCity=Pune, custAge=73]
Customer [custName=Trisha, custCity=Hyderabad, custAge=52]
Customer [custName=Trisha, custCity=Mangalore, custAge=45]

References:

Happy Coding !!
Happy Learning !!

Various ways to iterate over List of HashMap in Java
Various ways to iterate over HashMap of ArrayList in Java