Saturday, October 18, 2014

java.util.Comparator Usage Example

java.util.Comparator interface is used to manually define the criteria on which to compare objects. For example, same type of two objects can be compared based on their IDs or Names (for student objects) or color, price (for fruit objects).

The comparator interface has a method compareTo(Object1, Object2) which returns an int value based on the result of comparision

-1 if obj1 is less than obj2
0 if equal
+1 if obj1 is greater than obj2.

Here is an example:

import java.util.Arrays;
import java.util.Comparator;

//This is the class on which we'll be testing our comparators
class Student {

    private final String name;
    private final int id;
    
    //We've made static comparator Objects to make them Readily accessible
    public static Comparator<Student> NAME_COMPARE = new NameComparatorImplementation();
    public static Comparator<Student> ID_COMPARE = new IDComparatorImplementation();
    
    //This and the next inner class are the implementations of our comparators
    private static class NameComparatorImplementation implements Comparator<Student> {

        @Override
        public int compare(Student s1, Student s2) {
            return s1.name.compareTo(s2.name);
        }
    }

    private static class IDComparatorImplementation implements Comparator<Student> {

        @Override
        public int compare(Student s1, Student s2) {
            return s1.id < s2.id ? -1 : s1.id > s2.id ? 1 : 0;
        } 
    }
     
    public Student(String name, int id){
        this.name = name;
        this.id = id;
    }
    
    @Override
    public String toString(){
        return "Name: "+name+" ID: "+id;
    }
}

//This class manually tests the comparators (uses their comparator.compare() method to sort)
class ComparatorManualTester{
    
    //Insertion Sort used
    public static <T> void sort(T[] array, Comparator<T> comparator){
        for(int i=0;i<array.length-1;++i){
            for(int j=i+1;j>0;--j){
                if(comparator.compare(array[j], array[j-1])<0){
                    swap(array, j, j-1);
                }else break;
            }
        }
    }
    
    private static void swap(Object[] array, int index1, int index2){
        Object temp = array[index1];
        array[index1] = array[index2];
        array[index2] = temp;
    }
}

public class TestComparator {
    public static void main(String[] args){
        Student[] arrayOfStudents = new Student[]{new Student("C", 10), 
                                                  new Student("B", 1),
                                                  new Student("D", 155), 
                                                  new Student("A", 2),
                                                  new Student("F", 12)};
        
        //Arrays.sort(ArrayToSort, Comparator) - is predefined in java.util.Arrays
        //Sort by name using Arrays.sort(array, NameComparator) 
        Arrays.sort(arrayOfStudents, Student.NAME_COMPARE);
        System.out.println(Arrays.toString(arrayOfStudents));
        
        //Sort by ID using Arrays.sort(array, IDComparator)
        Arrays.sort(arrayOfStudents, Student.ID_COMPARE);
        System.out.println(Arrays.toString(arrayOfStudents));
        
        //Testing it by manually using the comparator in the static
        //sort method defined in ComparatorManualTester class.
        ComparatorManualTester.sort(arrayOfStudents, Student.NAME_COMPARE);
        System.out.println(Arrays.toString(arrayOfStudents));
        
        ComparatorManualTester.sort(arrayOfStudents, Student.ID_COMPARE);
        System.out.println(Arrays.toString(arrayOfStudents));
    } 
}
 
Output:
[Name: A ID: 2, Name: B ID: 1, Name: C ID: 10, Name: D ID: 155, Name: F ID: 12]
[Name: B ID: 1, Name: A ID: 2, Name: C ID: 10, Name: F ID: 12, Name: D ID: 155]
[Name: A ID: 2, Name: B ID: 1, Name: C ID: 10, Name: D ID: 155, Name: F ID: 12]
[Name: B ID: 1, Name: A ID: 2, Name: C ID: 10, Name: F ID: 12, Name: D ID: 155]

No comments:

Post a Comment