Feb 26, 2011

Sort elements in a Collection using Comparator Interface

Continuing our series of sorting elements in a Collection, this post makes use of the Comparator interface to sort the objects.

Key Idea
The
sort(List list, Comparator c)
method sorts the specified (modifiable) list in the order specified by the comparator

The Employee Java Bean below makes use of the EmployeeNameComparator class to sort the Employee elements in the list. Also, note the use of NullSafeComparator
package com.samples;

//File: Employee.java

public class Employee
{
    private String empName = null;
    private int empAge;

    public Employee(String name, int age)
    {
        this.empName = name;
        this.empAge = age;
    }

    public String getEmpName()
    {
        return empName;
    }

    public void setEmpName(String empName)
    {
        this.empName = empName;
    }

    public int getEmpAge()
    {
        return empAge;
    }

    public void setEmpAge(int empAge)
    {
        this.empAge = empAge;
    }
}
package com.samples;

//File: EmployeeTest.java

import java.awt.print.Printable;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class EmployeeTest
{
    public static void main(String args[])
    {
        Employee[] empArray = {
            new Employee("Spiderman", 29),
            new Employee("Superman", 30),
            new Employee(null, 0),
            new Employee("Batman", 35),
            new Employee("Perry", 25)
        };
        List<Employee> list = Arrays.asList(empArray);

        DebugPrint(list);
        Collections.sort(list, new EmployeeNameComparator(new NullSafeComparator(new StringComparator(), true)));
        DebugPrint(list);
        Collections.sort(list, new EmployeeAgeComparator());
        DebugPrint(list);
    }

    private static void DebugPrint(List<Employee> list)
    {
        System.out.println();
        System.out.println("== DEBUG ==");
        Iterator<Employee> itr = list.iterator();
        while (itr.hasNext())
        {
            Employee emp = itr.next();
            System.out.println("[Name]: " + emp.getEmpName() + "("   + emp.getEmpAge() + ")");
        }
    }
}
Important
The
NullSafeComparator
class prevents the program from crashing with
NullPointerException
when null is passed to the
compareTo()
function in
StringComparator
class. The class also takes care of the sorting of the
null
elements in the list
package com.samples;

//File: NullSafeComparator.java

import java.util.Comparator;

public class NullSafeComparator implements Comparator
{
    private Comparator comparator;
    private boolean nullsAreHigh;

    public NullSafeComparator(Comparator comparator, boolean nullsAreHigh)
    {
        this.comparator = comparator;
        this.nullsAreHigh = nullsAreHigh;
    }

    public int compare(Object o1, Object o2)
    {
        if(null == o1 && null == o2)return 0;
        if(null == o1 && null != o2)return (nullsAreHigh ? 1 : -1);
        if(null == o2 && null != o1)return (nullsAreHigh ? -1 : 1);

        return comparator.compare(o1, o2);
    }
}

package com.samples;

//File: EmployeeNameComparator

import java.util.Comparator;

public class EmployeeNameComparator implements Comparator<Employee>
{
    private Comparator comparator;

    public EmployeeNameComparator(Comparator comparator)
    {
        this.comparator = comparator;
    }

    public int compare(Employee o1, Employee o2)
    {
        return comparator.compare(o1.getEmpName(), o2.getEmpName());
    }
}
package com.samples;

//File: StringComparator.java

import java.util.Comparator;

public class StringComparator implements Comparator<String>
{
    public int compare(String o1, String o2)
    {
        return o1.compareTo(o2);
    }

}
package com.samples;

//File: EmployeeAgeComparator.java

import java.util.Comparator;

public class EmployeeAgeComparator implements Comparator<Employee>
{
    public EmployeeAgeComparator()
    {
    }

    public int compare(Employee o1, Employee o2)
    {
        if(o1.getEmpAge() == o2.getEmpAge())
        {
            return 0;
        }

        return o1.getEmpAge() > o2.getEmpAge() ? 1 : -1;
    }
}
The sample run of the program shows the Employee list sorted by name and then sorted by age.
Output:

No comments :

Post a Comment