Archives for 

Comparable & Comparator interfaces

Comparable & Comparator are two important interfaces in Java. These are used in sorting objects on collections like TreeSet.

Comparator interface in Java

The Comparator  interface in Java is widely using in sorting objects in  data structures like TreeSet or TreeMap.The Comparator interface is having one abstract method compare(Object arg1,Object arg2) .The compare() method returns an integer value.The concept will become clear once we do an example.

If we are using the Comparator instance for sorting a number of objects in TreeSet or TreeMap , then  we need to pass the Comparator instance while initializing the data structure.(unlike from the case of Comparable ).

In this example we are planning to put few Student objects in a TreeSet. We need those objects in ascending order of attribute ‘id’. Now see the Student.java first.

Now we need a Comparator unit . The compare() method should do the comparison to arrange the TreeSet elements in ascending order.

Now let us see the ComparatorSample.java. It creates a TreeSet object with the StudentComparator instance as argument.

The addItems() method is adding few Student objects to the TreeSet. The displayItems() method is displaying the contents. The output is in a sorted order. The compare() method of StudentComparator.java makes the TreeSet elements in the ascending order of attribute ‘id’.

Output

In ascending order

Id = 1 ; Name = Karthik

Id = 2 ; Name = Bijoy

Id = 3 ; Name = Dexter

Id = 4 ; Name = Sasi

If we reverse the logic in compare() method(change it to  return student2.getId() – student1.getId()) ,then  the TreeSet will be in descending order

See Related Topics:

Collections in Java

Threading in Java

Comparable vs Comparator in Java

Comparable in Java