Skip to content

Comparators

Santhosh Kumar Tekuri edited this page Mar 18, 2015 · 1 revision

DefaultComparator:

jlibs.core.util.DefaultComparator is default implementation of java.util.Comparator;

Its implementation is null friendly where null is treated less than non-null:

import jlibs.core.util.DefaultComparator;

Comparator<String> comp = new DefaultComparator<String>();
int result1 = comp.compareTo(null, "helloworld"); // returns -1
int result2 = comp.compare("helloworld", null); // returns 1
int result3 = comp.compare(null, null); // returns 0

The implemenation of DefaultComparator works for any objects implementing java.util.Comparable:

Comparator<Integer> comp = new DefaultComparator<Integer>(); // Integer implements Comparable
int result = comp.compare(10, 7); // returns 3

You can extend DefaultComparable for any objects that doesn't implement Comparable:

class Employee{
    int marks;
    int age;

    public Employee(int marks, int age){
        this.marks = marks;
        this.age = age;
    }
}

class EmployeeAgeComparator extends DefaultComparator<Employee>{
    @Override
    protected int _compare(@NotNull Employee emp1, @NotNull Employee emp2){
        return emp1.age - emp2.age;
    }
}

the compare(...) method in DefaultComparator is final. the compare(...) takes care of
comparing values involving nulls. If both arguments are non-null,
then it delegates the comparison to _compare(...);

So it is guaranteed that, both arguments of _compare(...) are non-null;

ReverseComparator:

jlibs.core.util.ReverseComparator can be used to sort objects in reverse order;

import jlibs.core.util.ReverseComparator;

String arr[] = { "c", "java", "c++", "jsp" };
Arrays.sort(arr, new ReverseComparator<String>());
System.out.println(Arrays.asList(arr)); // prints [jsp, java, c++, c]

to sort employees, in descending order of their ages:

List<Employee> employees = ...
Collections.sort(employees, new ReverseComparator<Employee>(new EmployeeAgeComparator()));

i.e ReverseComparator has constructor which takes comparator implementation to be used;
The default constructor uses DefaultComparator implicitly;

ChainedComparator:

Let us say, you want to sort list of employees by their marks. and If there are more than one employee with same marks sort them by their age.

To do this kind of chained comparison, ChainedComparator will become handy;

import jlibs.core.util.ChainedComparator;

class EmployeeMarksComparator extends DefaultComparator<Employee>{
@Override
protected int _compare(@NotNull Employee emp1, @NotNull Employee emp2){
return emp1.marks - emp2.marks;
}
}

List<Employee> employees = null;
Collections.sort(employees, new ChainedComparator<Employee>(new EmployeeMarksComparator(), new EmployeeAgeComparator()));

Your comments are welcomed;

Clone this wiki locally