Sorting Arrays using Comparable and Comparator

In this article, we will discuss how to sort Arrays using Arrays class’s utility sort() method

  1. default natural sorting order for primitive type Arrays
  2. java.lang.Comparable interface –> for natural ordering of Object Arrays
  3. java.util.Comparator interface –> for customized sorting of Object Arrays

 

Cautions:

  1. For primitive types, only default natural ordering is possible
  2. For objects, both default natural ordering as well as customized sorting is possible using Comparable and Comparator interfaces

 

 

Case 1: Natural-ordering for primitive type Arrays

Method signature:

public static void sort(primitive[] p);

PrimitveNaturalSortingOfArrays.java

package in.bench.resources.java.collection;

import java.util.Arrays;

public class PrimitveNaturalSortingOfArrays {

	public static void main(String[] args) {

		Integer[] intArrays = {31, 83, 53, 97, 29, 7, 13,  47, 79};
		String[] strArrays = {
				"James", 
				"Bond", 
				"Michael", 
				"Pups", 
				"Jackson", 
				"Bird"
		};

		System.out.println("Before sorting: Integer Arrays\n");

		// printing Integer Arrays
		System.out.println(Arrays.toString(intArrays));

		// sorting Arrays using
		Arrays.sort(intArrays);

		System.out.println("\nAfter sorting: Integer Arrays\n");

		// printing Integer Arrays
		System.out.println(Arrays.toString(intArrays));


		System.out.println("\n\n\nBefore sorting: String Arrays\n");

		// printing Integer Arrays
		System.out.println(Arrays.toString(strArrays));

		// sorting Arrays using
		Arrays.sort(strArrays);

		System.out.println("\nAfter sorting: String Arrays\n");

		// printing Integer Arrays
		System.out.println(Arrays.toString(strArrays));
	}
}

Output:

Before sorting: Integer Arrays

[31, 83, 53, 97, 29, 7, 13, 47, 79]

After sorting: Integer Arrays

[7, 13, 29, 31, 47, 53, 79, 83, 97]



Before sorting: String Arrays

[James, Bond, Michael, Pups, Jackson, Bird]

After sorting: String Arrays

[Bird, Bond, Jackson, James, Michael, Pups]

 

Case 2: Natural ordering for Object Arrays; using Comparable interface

Method signature:

public static void sort(Object[] objectArray);

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 "["
				+ "Id=" + customerId 
				+ ", Name=" + 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 Customer Arrays and
  • prints customer Arrays in ascending order of customer names

NaturalSortingOfObjectArrays.java

package in.bench.resources.java.collection;

import java.util.Arrays;

public class NaturalSortingOfObjectArrays {

	public static void main(String[] args) {

		// creating Customer Arrays of initial size 4
		Customer[]  customers = new Customer[4];

		// initializing each customer objects
		customers[0] = new Customer(102, "Nandan Nilekeni");
		customers[1] = new Customer(104, "Shibulal");
		customers[2] = new Customer(101, "Narayan Murthy");
		customers[3] = new Customer(103, "Kris Gopalakrishnan");

		System.out.println("Before sorting: Customer Arrays\n");

		// printing Integer Arrays
		System.out.println(Arrays.toString(customers));

		// sorting Arrays using
		Arrays.sort(customers);

		System.out.println("\nAfter sorting: Customer Arrays "
				+ "according to ascending order of names\n");

		// printing Integer Arrays
		System.out.println(Arrays.toString(customers));
	}
}

Output:

Before sorting: Customer Arrays

[[Id=102, Name=Nandan Nilekeni], [Id=104, Name=Shibulal], 
[Id=101, Name=Narayan Murthy], [Id=103, Name=Kris Gopalakrishnan]]

After sorting: Customer Arrays acc. to ascending order of names

[[Id=103, Name=Kris Gopalakrishnan], [Id=102, Name=Nandan Nilekeni], 
[Id=101, Name=Narayan Murthy], [Id=104, Name=Shibulal]]

 

Case 3: Customized Sorting for Object Arrays; using Comparator interface

Method signature:

public static void sort(Object[] objectArray, 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 "["
				+ "Id=" + customerId 
				+ ", Name=" + customerName
				+ "]";
	}
}

CustomerIdComparator.java

  • This is separate class which implements Comparator interface providing customized sorting logic
  • compare() method provides sorting logic, according to ascending order of 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 o1.customerId - o2.customerId;
	}
}

Main class

  • This class uses above customer POJO and customized sorting logic class
  • implementing comparator interface, to store objects inside Customer Arrays
  • sorting according to comparator (i.e.; natural ordering of customer Id)
  • prints customer objects in ascending order of customer Id

CustomizedSortingOfObjectArrays.java

package in.bench.resources.java.collection;

import java.util.Arrays;

public class CustomizedSortingOfObjectArrays {

	public static void main(String[] args) {

		// creating Customer Arrays of initial size 4
		Customer[]  customers = new Customer[4];

		// initializing each customer objects
		customers[0] = new Customer(102, "Nandan Nilekeni");
		customers[1] = new Customer(104, "Shibulal");
		customers[2] = new Customer(101, "Narayan Murthy");
		customers[3] = new Customer(103, "Kris Gopalakrishnan");

		System.out.println("Before sorting: Customer Arrays\n");

		// printing Integer Arrays
		System.out.println(Arrays.toString(customers));

		// sorting Arrays using
		Arrays.sort(customers, new CustomerIdComparator());

		System.out.println("\nAfter sorting: Customer Arrays "
				+ "according to ascending order of Id\n");

		// printing Integer Arrays
		System.out.println(Arrays.toString(customers));
	}
}

Output:

Before sorting: Customer Arrays

[[Id=102, Name=Nandan Nilekeni], [Id=104, Name=Shibulal], 
[Id=101, Name=Narayan Murthy], [Id=103, Name=Kris Gopalakrishnan]]

After sorting: Customer Arrays acc. to ascending order of Id

[[Id=101, Name=Narayan Murthy], [Id=102, Name=Nandan Nilekeni], 
[Id=103, Name=Kris Gopalakrishnan], [Id=104, Name=Shibulal]]

 

References:

 

Happy Coding !!
Happy Learning !!

Searching element from Arrays using Binary Search Algorithm
Arrays class