June 12, 2011

Java Collections Framework: TreeSet Example with Comparable and Comparator implementation

The TreeSet implementation of the Set interface maintains a sorted collection of unique objects. The custom sort order is determined by implementing either the Comparable interface or the Comparator interface.

In case of the Comparable interface, the class (objects of which will be added to the TreeSet) has to implement the interface.

In case of the Comparator interface. an external class implements the interface. The Comparator allows creating a custom sort order for objects of a 3rd party class.

TreeSet code example with Comparable to compare objects for custom sort order

package info.icontraining.collections;

import java.util.*;

public class TreeSetExample {

   public static void main(String[] args) {
 
      Set customers = new TreeSet();

      customers.add(new Customer("Dinesh", "Atlanta"));      
      customers.add(new Customer("Tanvi", "Norcross"));
      customers.add(new Customer("Laksh", "Duluth"));
  
      for(Customer c: customers) {
         System.out.print(c.getCustomerName() + " | ");
         System.out.println(c.getCustomerCity());      
      }  
     
      customers.add(new Customer("Dinesh", "Alpharetta"));

      System.out.println();

      for(Customer c: customers) {
         System.out.print(c.getCustomerName() + " | ");
         System.out.println(c.getCustomerCity());      
      }    
   }
}

package info.icontraining.collections;

public class Customer implements Comparable {

   private String customerName;
   private String customerCity;
 
   public Customer(String customerName, String customerCity) {
      this.customerName = customerName;
      this.customerCity = customerCity;
   }
 
   public int compareTo(Customer customer) {
      int nameOrder = this.customerName.compareTo(customer.customerName);

      if (nameOrder == 0)
         return this.customerCity.compareTo(customer.customerCity);
  
      return nameOrder;
   }
 
   public String getCustomerName() {
      return this.customerName;
   }
 
   public String getCustomerCity() {
      return this.customerCity;
   }
}

TreeSet code example with Comparator to compare objects for custom sort order

Using the Comparator interface entails creating a new class to implement the interface. The Comparator should be used in the situation where the Customer class is a 3rd party class whose source code is unavailable to us.

package info.icontraining.collections;

import java.util.Comparator;

public class CustomerComparator implements Comparator {

   public int compare(Customer c1, Customer c2) {
      int nameOrder = c1.getCustomerName().compareTo(c2.getCustomerName());
  
      if (nameOrder == 0)
         return c1.getCustomerCity().compareTo(c2.getCustomerCity());
  
      return nameOrder;
   }
}

Also make the following changes to run the example with Comparator instead of Comparable,

1) From the Customer class, remove the implements Comparable

2) In the TreeSetExample class, replace the following line to instantiate the TreeSet

Set<Customer> customers = new TreeSet<Customer>();

with

Set<Customer> customers = new TreeSet<Customer>(new CustomerComparator());

2 comments:

  1. Nice article you have covered the topic well with code example just to add while using comparable interface in Java and overriding compareTo method its worth noting that compareTo must be compatible with s equals method in Java i.e. if two objects are equal via equals method compareTo method must return "0" for them, failing this may result in some subtle bug when you store those objects in collection class like TreeSet and TreeMap.

    Source: How to use Comparator and Comparable in Java

    ReplyDelete
  2. This is a woderful example, a perfectly explained example. Thanks

    ReplyDelete