Arrays.sort to sort arrays by implementing Comparator and how Comparator of superclass can be used by subclasses in java


In this Collection framework tutorial we will learn how to sort arrays(by implementing Comparator and Comparator) with lots of examples and programs in java.


Contents of page :
  • Example/Program 1 to sort Integer array using Arrays.sort (by default Arrays.sort will sort array in ascending order) in java
  • Example/Program 2 to sort Integer array by using Arrays.sort (we will define Comparator to sort elements in descending order) in java
  • Example/Program 3 to sort Employee array using Arrays.sort in ascending order on basis of name and id by implementing Comparator interface in java
  • Example/Program 4 to understand Comparator of superclass can be used by subclasses in java.

Arrays.Sort() internally uses Merge Sort in java.
Merge sort calls overridden compare method of Comparator interface for comparison of values (if any).

Must know fact :
If number of elements is less than 7 then Insertion Sort is used rather than Merge Sort (because in case elements are less than 7 it offers better time complexity) in java.

Example/Program 1 to sort Integer array using Arrays.sort (by default Arrays.sort will sort array in ascending order) in java

import java.util.Arrays;
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class ArraysSortExample {
   public static void main(String...a){
       Integer intArray[]={2,3,1};
      
       System.out.print("Array before sorting : ");
       for(int i: intArray){
          System.out.print(i+" ");
       }
       Arrays.sort(intArray);
      
       System.out.print("\nArray after sorting : ");
       for(int i: intArray){
          System.out.print(i+" ");
       }
      
   }
}
/*OUTPUT
Array before sorting : 2 3 1
Array after sorting : 1 2 3
*/

Example/Program 2 to sort Integer array by using Arrays.sort (we will define Comparator to sort elements in descending order) in java
import java.util.Arrays;
import java.util.Comparator;
class SortDescending implements Comparator<Integer> {
   @Override
   public int compare(Integer o1, Integer o2) {
          //using Comparator to sort array in descending order.
          return o2.compareTo(o1);
   }
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class ArraysSortExample {
   public static void main(String...a){
       Integer intArray[]={2,3,1};
      
       System.out.print("Array before sorting : ");
       for(int i: intArray){
          System.out.print(i+" ");
       }
       Arrays.sort(intArray, new SortDescending());
      
       System.out.print("\nArray after sorting in descending order : ");
       for(int i: intArray){
          System.out.print(i+" ");
       }
      
   }
}
/*OUTPUT
Array before sorting : 2 3 1
Array after sorting in descending order : 3 2 1
*/

Example/Program 3 to sort Employee array using Arrays.sort in ascending order on basis of name and id by implementing Comparator interface in java

import java.util.Arrays;
import java.util.Comparator;
class Employee{
   String name;
   String id;
  
   public Employee() {}
  
   public Employee(String name, String id) {
       this.name = name;
       this.id = id;
   }
  
  
   @Override
   public String toString() {
       return "Employee{" + "name=" + name + ", id=" + id  + '}';
   }
  
}
class ComparatorName implements Comparator<Employee>{
   @Override
   public int compare(Employee obj1, Employee obj2) {
      //sort Employee on basis of name(ascending order)
      return obj1.name.compareTo(obj2.name);
   }
  
}
class ComparatorId implements Comparator<Employee>{
   @Override
   public int compare(Employee obj1, Employee obj2) {
      //sort Employee on basis of id(ascending order)
      return obj1.id.compareTo(obj2.id);
   }
  
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class ArraysSortExample {
   public static void main(String[] args) {
          Employee emp1 = new Employee("sam", "4");
          Employee emp2 = new Employee("amy", "2");
          Employee emp3 = new Employee("brad", "1");
          Employee employeeArray[] = { emp1, emp2, emp3 };
          System.out.print(" employeeArray Before sorting : \n");
          for (Employee emp : employeeArray) {
                 System.out.print(emp + "  ");
          }
          Arrays.sort(employeeArray, new ComparatorName());
          System.out.println("\n\n employeeArray after sorting on basis of "
                       + "name(ascending order) : ");
          for (Employee emp : employeeArray) {
                 System.out.print(emp + "  ");
          }
          Arrays.sort(employeeArray, new ComparatorId());
          System.out.println("\n\n employeeArray after sorting on basis of "
                       + "id(ascending order) : ");
          for (Employee emp : employeeArray) {
                 System.out.print(emp + "  ");
          }
   }
}
/*OUTPUT
employeeArray Before sorting :
[Employee{name=sam, id=4}, Employee{name=amy, id=2}, Employee{name=brad, id=1}]
employeeArray after sorting on basis of name(ascending order) :
[Employee{name=amy, id=2}, Employee{name=brad, id=1}, Employee{name=sam, id=4}]
employeeArray after sorting on basis of id(ascending order) :
[Employee{name=brad, id=1}, Employee{name=amy, id=2}, Employee{name=sam, id=4}]
*/

Example/Program 4 to understand Comparator of superclass can be used by subclasses in java

Animal is superclass of Dog and Lion.
dogArray is array of dogs.
AnimalComparator is a Comparator of Animal class [ class AnimalComparator implements Comparator<Animal> ]

We will be using Arrays.sort(dogArray, new AnimalComparator()); in program.

Method definition of sort method in java.util.Arrays is -
public static <T> void sort(T[] a, Comparator<? super T> c)

So, what do you mean by second parameter  Comparator<? super T> c

Let’s understand first parameter -
T[] a   
dogArray has been passed as parameter which is array of Dog, and Dog extends Animal. So,
T is Dog, and
T[] is dogArray.

Now, let’s understand second parameter -
Comparator<? super T> c  
In the program, following 2 lines have been used >
class Dog extends Animal (Animal is superclass of Dog),
class AnimalComparator implements Comparator<Animal>
(AnimalComparator is a Comparator of Animal class but it can be used by subclasses (i.e. Dog and Lion) as well.)

Full program -
import java.util.Arrays;
import java.util.Comparator;
/**
* Animal class
*/
class Animal{
   Integer height;
}
/**
* Lion class
*/
class Lion extends Animal{
   Lion(Integer height){
          this.height=height;
   }
  
   @Override
   public String toString() {
          return "Lion [height=" + height + "]";
   }
}
/**
* Dog class
*/
class Dog extends Animal{
   Dog(Integer height){
          this.height=height;
   }  
   @Override
   public String toString() {
          return "Dog [height=" + height + "]";
   }
}
/**
* Comparator to sort animal's height in ascending order.
*/
class AnimalComparator implements Comparator<Animal> {
   @Override
   public int compare(Animal o1, Animal o2) {
          //using Comparator to sort animal's height in ascending order.
          return o1.height.compareTo(o2.height);
   }
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class ArraysSortExample {
   public static void main(String...a){
System.out.println("-----Sorting Lion's height -- using AnimalComparator-----");
      Lion lion1=new Lion(3);
      Lion lion2=new Lion(1);
      Lion lion3=new Lion(2);
      Lion lionArray[]={lion1, lion2, lion3};
      
          System.out.print(" lionArray before sorting : \n");
          for (Animal animal : lionArray) {
                 System.out.print(animal + "  ");
          }
          Arrays.sort(lionArray, new AnimalComparator());
          System.out.println("\n\n lionArray after sorting on basis of "
                       + "height(ascending order) : ");
          for (Animal animal : lionArray) {
                 System.out.print(animal + "  ");
          }
System.out.println("\n\n\n------Sorting Dog's height -- using AnimalComparator----");
      
      Dog dog1=new Dog(2);
      Dog dog2=new Dog(1);
      Dog dog3=new Dog(3);
      Dog dogArray[]={dog1, dog2, dog3};
      
          System.out.print(" dogArray before sorting : \n");
          for (Animal animal : dogArray) {
                 System.out.print(animal + "  ");
          }
          Arrays.sort(dogArray, new AnimalComparator());
          System.out.println("\n\n dogArray after sorting on basis of "
                       + "height(ascending order) : ");
          for (Animal animal : dogArray) {
                 System.out.print(animal + "  ");
          }
      
   }
}
/*OUTPUT
----------Sorting Lion's height -- using AnimalComparator----------
lionArray before sorting :
Lion [height=3]  Lion [height=1]  Lion [height=2]
lionArray after sorting on basis of height(ascending order) :
Lion [height=1]  Lion [height=2]  Lion [height=3]
--------Sorting Dog's height -- using AnimalComparator---------
dogArray before sorting :
Dog [height=2]  Dog [height=1]  Dog [height=3]
dogArray after sorting on basis of height(ascending order) :
Dog [height=1]  Dog [height=2]  Dog [height=3]
*/

So in this Collection framework tutorial we learned how to sort arrays(by implementing Comparator and Comparator) with lots of examples and programs in java.

RELATED LINKS>

Collection in java

Collection - List, Set and Map all properties in tabular form in java


Sorting Collection by implementing comparator and Comparable, using TreeMap and TreeSet, Collections.sort and Arrays.sort in java >

Comparable vs Comparator - differences and sorting list by implementing Comparable and Comparator in classes and inner classes in java


Sort Set by using TreeSet and by implementing Comparator and Comparable interface in java


Sort Map by key in Ascending and descending order by implementing Comparator interface and overriding its compare method and using TreeMap in java


Sort Map by value in Ascending and descending order by implementing Comparator interface and overriding its compare method in java





Set hierarchy in java - Detailed - HashSet, CopyOnWriteArraySet, LinkedHashSet, TreeSet, ConcurrentSkipListSet, EnumSet classes


No comments:

Post a Comment