Sorting Example

  • Sorting with Array
    // toSort = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 };
    Arrays.sort(toSort);The unsorted array is now fully sorted:
    [1, 5, 7, 66, 88, 89, 123, 200, 255]
  • Sorting a List
    List<Integer> toSortList = Integer.asList(toSort);
    Collections.sort(toSortList);

Comparable

Comparable is implemented by a class in order to be able to comparing object of itself with some other objects. The class itself must implement the interface in order to be able to compare its instance(s). The method required for implementation is compareTo().

class HDTV implements Comparable<HDTV> { 

  private int size; 
  private String brand; 
  
  public HDTV(int size, String brand) { 
    this.size = size; 
    this.brand = brand; 
  } 
  
  public int getSize() { 
    return size; 
  } 
  
  @Override 
  public int compareTo(HDTV tv) { 
  
    if (this.getSize() > tv.getSize()){ 
      return 1; 
    }
    else if (this.getSize() < tv.getSize()){ 
      return -1; else return 0; 
    }
  }   
} 


public class Main { 

  public static void main(String[] args) { 
  
    HDTV tv1 = new HDTV(55, "Samsung"); 
    HDTV tv2 = new HDTV(60, "Sony"); 
    
    if (tv1.compareTo(tv2) > 0) {     
      System.out.println(tv1.getBrand() + " is better.");  
    } 
    else { 
      System.out.println(tv2.getBrand() + " is better."); 
    } 
  } 
}

 

Comparator

Comparator can be used if you want to compare objects based on certain attributes/fields. For example, 2 persons can be compared based on `height` or `age` etc. (this can not be done using comparable.). The method required to implement is compare(). One common use of Comparator is sorting. Both Collections and Arrays classes provide a sort method which use a Comparator.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
 
class HDTV {
  private int size;
  private String brand;
 
  public HDTV(int size, String brand) {
    this.size = size;
    this.brand = brand;
  }
 
  public int getSize() {
    return size;
  }
 
  public String getBrand() {
    return brand;
  }
}
 
class SizeComparator implements Comparator<HDTV> {

  @Override
  public int compare(HDTV tv1, HDTV tv2) {
    int tv1Size = tv1.getSize();
    int tv2Size = tv2.getSize();
 
    if (tv1Size > tv2Size) {
      return 1;
    } else if (tv1Size < tv2Size) {
      return -1;
    } else {
      return 0;
    }
  }
}
 
public class Main {
   public static void main(String[] args) {
   HDTV tv1 = new HDTV(55, "Samsung");
   HDTV tv2 = new HDTV(60, "Sony");
   HDTV tv3 = new HDTV(42, "Panasonic");
 
   ArrayList<HDTV> al = new ArrayList<HDTV>();
   al.add(tv1);
   al.add(tv2);
   al.add(tv3);
 
   Collections.sort(al, new SizeComparator());

   for (HDTV a : al) {
     System.out.println(a.getBrand());
   }
 }
}

 

Comparable vs Comparator

  • Comparable is meant for objects with natural ordering which means the object itself must know how it is to be ordered. For example Roll Numbers of students. Whereas, Comparator interface sorting is done through a separate class.
  • Logically, Comparable interface compares “this” reference with the object specified and Comparator in Java compares two different class objects provided.
  • If any class implements Comparator interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method.

To summarize, if sorting of objects needs to be based on natural order then use Comparable whereas if you sorting needs to be done on attributes of different objects, then use Comparator.

 

Sorting order

Collections.sort() preserve the order of equal elements. From JAVA documentation:

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

In other words, if the entries are ordered by date before the sort(), they will stay ordered by date within each category after the sort().