Showing posts with label Comparator. Show all posts
Showing posts with label Comparator. Show all posts

Wednesday, December 21, 2011

How to implement ReverseOrderComparator


Java.Util.Comparator is an interface used for sorting collections. In previous example, we used a MultyField Comparator to sort a list in ascending order by multiple fields. In this example, we will implement a reverse order multy field Comparator in order to achieve a sorting in descending order or in other words in reverse order of whatever is implemented in the Comparator. This can be achieved just by a single line of code as
Comparator c= Collections.reverseOrder(new mployeeMultyFieldComparator());
 This example is almost a replica of the previous example. It consists of the following 3 classes.

Employee.java:

package com.soft.model;

public class Employee{
private String name;
private String department;
private int age;
public String getName() {
            return name;
}
public void setName(String name) {
            this.name = name;
}
public String getDepartment() {
            return department;
}
public void setDepartment(String department) {
            this.department = department;
}
public int getAge() {
            return age;
}
public void setAge(int age) {
            this.age = age;
}

}



EmployeeMultyFieldComparator.java:

package com.soft.model;

import java.util.Comparator;

public class EmployeeMultyFieldComparator implements Comparator{

            @Override
            public int compare(Object obj1, Object obj2) {
                        Employee e1=(Employee)obj1;
                        Employee e2=(Employee)obj2;
                        if(e1.getName().compareTo(e2.getName())==0){
                                    if(e1.getDepartment().compareTo(e2.getDepartment())==0){
                                                return e1.getAge()-e2.getAge();
                                    }else{
                                                return e1.getDepartment().compareTo(e2.getDepartment());
                                    }
                        }else{
                                    return e1.getName().compareTo(e2.getName());
                        }
            }

}


MultyFieldComparatorExample.java:

package com.soft.examples;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.soft.model.Employee;
import com.soft.model.EmployeeMultyFieldComparator;

public class MultyFieldComparatorExample {
            public static void main(String[] args) {
                        List<Employee> list= new ArrayList<Employee>();
                        Employee e=new Employee();
                        e.setName("Danial Fritz");
                        e.setDepartment("Field Based Development");
                        e.setAge(36);
                        list.add(e);
                        e=new Employee();
                        e.setName("Denis Khoo");
                        e.setDepartment("Project Management");
                        e.setAge(30);
                        list.add(e);
                        e=new Employee();
                        e.setName("Joe Kum");
                        e.setDepartment("Adminstration");
                        e.setAge(40);
                        list.add(e);
                        e=new Employee();
                        e.setName("Anil Kumar");
                        e.setDepartment("Information Technology");
                        e.setAge(26);
                        list.add(e);
                        e=new Employee();
                        e.setName("Anil Kumar");
                        e.setDepartment("Information Technology");
                        e.setAge(26);
                        list.add(e);
                        e=new Employee();
                        e.setName("Anil Kumar");
                        e.setDepartment("Information Technology");
                        e.setAge(25);
                        list.add(e);
                        e=new Employee();
                        e.setName("Anil Kumar");
                        e.setDepartment("Project Management");
                        e.setAge(26);
                        list.add(e);
                        System.out.println("************ Before Sorting ***********");
                        for (int i=0;i< list.size();i++){
                                    System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
                        }
                        System.out.println("************ Name, Department, Age Sorting through Comparator ***********");
                        Collections.sort(list,new EmployeeMultyFieldComparator());
                        for (int i=0;i< list.size();i++){
                                    System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
                        }

System.out.println("** Name, Department, Age Sorting through Comparator In Descending Order**");
Collections.sort(list,Collections.reverseOrder(new EmployeeMultyFieldComparator()));
for (int i=0;i< list.size();i++){
System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
}
                       
            }
}

Output:
************ Before Sorting ***********
Danial Fritz   ----- Field Based Development   ----- 36
Denis Khoo     ----- Project Management        ----- 30
Joe Kum        ----- Adminstration             ----- 40
Anil Kumar     ----- Information Technology    ----- 26
Anil Kumar     ----- Information Technology    ----- 26
Anil Kumar     ----- Information Technology    ----- 25
Anil Kumar-----Project Management-----26

****** Name, Department, Age Sorting through Comparator *******

Anil Kumar     ----- Information Technology     ----- 25
Anil Kumar     ----- Information Technology     ----- 26
Anil Kumar     ----- Information Technology     ----- 26
Anil Kumar     ----- Project Management         ----- 26
Danial Fritz   ----- Field Based Development    ----- 36
Denis Khoo     ----- Project Management         ----- 30
Joe Kum        ----- Adminstration              ----- 40

** Name, Department, Age Sorting through Comparator in Descending Order**

Joe Kum        ----- Adminstration                     ----- 40
Denis Khoo   ----- Project Management           ----- 30
Danial Fritz   ----- Field Based Development   ----- 36
Anil Kumar   ----- Project Management           ----- 26
Anil Kumar   ----- Information Technology     ----- 26
Anil Kumar   ----- Information Technology     ----- 26
Anil Kumar   ----- Information Technology     ----- 25

An example of a simple MultyFieldComparator can be found at
You may also find the following articles helpful.


Tuesday, December 20, 2011

How to implement MultyFieldComparator

Java.Util.Comparator is an interface used for sorting collections. In previous example, we used comparator for sorting by only one field. In this example, we will see a more complex comparator which can be used to sort a list of employees based on the name, then on department and then on age. The example consists of the following 3 classes.

Employee.java:

package com.soft.model;

public class Employee{
private String name;
private String department;
private int age;
public String getName() {
            return name;
}
public void setName(String name) {
            this.name = name;
}
public String getDepartment() {
            return department;
}
public void setDepartment(String department) {
            this.department = department;
}
public int getAge() {
            return age;
}
public void setAge(int age) {
            this.age = age;
}

}



EmployeeMultyFieldComparator.java:

package com.soft.model;

import java.util.Comparator;

public class EmployeeMultyFieldComparator implements Comparator{

            @Override
            public int compare(Object obj1, Object obj2) {
                        Employee e1=(Employee)obj1;
                        Employee e2=(Employee)obj2;
                        if(e1.getName().compareTo(e2.getName())==0){
                                    if(e1.getDepartment().compareTo(e2.getDepartment())==0){
                                                return e1.getAge()-e2.getAge();
                                    }else{
                                                return e1.getDepartment().compareTo(e2.getDepartment());
                                    }
                        }else{
                                    return e1.getName().compareTo(e2.getName());
                        }
            }

}


MultyFieldComparatorExample.java:

package com.soft.examples;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.soft.model.Employee;
import com.soft.model.EmployeeMultyFieldComparator;

public class MultyFieldComparatorExample {
            public static void main(String[] args) {
                        List<Employee> list= new ArrayList<Employee>();
                        Employee e=new Employee();
                        e.setName("Danial Fritz");
                        e.setDepartment("Field Based Development");
                        e.setAge(36);
                        list.add(e);
                        e=new Employee();
                        e.setName("Denis Khoo");
                        e.setDepartment("Project Management");
                        e.setAge(30);
                        list.add(e);
                        e=new Employee();
                        e.setName("Joe Kum");
                        e.setDepartment("Adminstration");
                        e.setAge(40);
                        list.add(e);
                        e=new Employee();
                        e.setName("Anil Kumar");
                        e.setDepartment("Information Technology");
                        e.setAge(26);
                        list.add(e);
                        e=new Employee();
                        e.setName("Anil Kumar");
                        e.setDepartment("Information Technology");
                        e.setAge(26);
                        list.add(e);
                        e=new Employee();
                        e.setName("Anil Kumar");
                        e.setDepartment("Information Technology");
                        e.setAge(25);
                        list.add(e);
                        e=new Employee();
                        e.setName("Anil Kumar");
                        e.setDepartment("Project Management");
                        e.setAge(26);
                        list.add(e);
                        System.out.println("************ Before Sorting ***********");
                        for (int i=0;i< list.size();i++){
                                    System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
                        }
                        System.out.println("************ Name, Department, Age Sorting through Comparator ***********");
                        Collections.sort(list,new EmployeeMultyFieldComparator());
                        for (int i=0;i< list.size();i++){
                                    System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
                        }
                       
            }
}

Output:
************ Before Sorting ***********
Danial Fritz   ----- Field Based Development   ----- 36
Denis Khoo     ----- Project Management        ----- 30
Joe Kum        ----- Adminstration             ----- 40
Anil Kumar     ----- Information Technology    ----- 26
Anil Kumar     ----- Information Technology    ----- 26
Anil Kumar     ----- Information Technology    ----- 25
Anil Kumar-----Project Management-----26

****** Name, Department, Age Sorting through Comparator *******

Anil Kumar     ----- Information Technology     ----- 25
Anil Kumar     ----- Information Technology     ----- 26
Anil Kumar     ----- Information Technology     ----- 26
Anil Kumar     ----- Project Management         ----- 26
Danial Fritz   ----- Field Based Development    ----- 36
Denis Khoo     ----- Project Management         ----- 30
Joe Kum        ----- Adminstration              ----- 40

An example of a simple Comparator can be found at

You may also find the following articles helpful.


How to implement a java.UtilComparator

Java.Util.Comparator is an interface used for sorting collections. The classes implementing Comparators must implement the compare() method. Here is a simple example of how a comparator can be used. In this example we have a simple pojo named Employee.java, 3 simple Comparator classes and a main class to demonstrate the functionality.

Employee.java:

package com.soft.model;

public class Employee {
private String name;
private String department;
private int age;
public String getName() {
            return name;
}
public void setName(String name) {
            this.name = name;
}
public String getDepartment() {
            return department;
}
public void setDepartment(String department) {
            this.department = department;
}
public int getAge() {
            return age;
}
public void setAge(int age) {
            this.age = age;
}

}

EmployeeNameComparator.java:

package com.soft.model;

import java.util.Comparator;

public class EmployeeNameComparator implements Comparator{

            public int compare(Object obj1, Object obj2) {
                        Employee e1=(Employee)obj1;
                        Employee e2=(Employee)obj2;
                        return e1.getName().compareTo(e2.getName());
            }
}


EmployeeDepartmentComparator.java

package com.soft.model;

import java.util.Comparator;

public class EmployeeDepartmentComparator implements Comparator {

            public int compare(Object obj1, Object obj2) {
                        Employee e1=(Employee)obj1;
                        Employee e2=(Employee)obj2;
                        return e1.getDepartment().compareTo(e2.getDepartment());
            }
}


EmployeeAgeComparator.java:

package com.soft.model;

import java.util.Comparator;

public class EmployeeAgeComparator implements Comparator{

            public int compare(Object obj1, Object obj2) {
                        Employee e1=(Employee)obj1;
                        Employee e2=(Employee)obj2;
                        if(e1.getAge()>e2.getAge()) {
                                    return 1;
                        }else if(e1.getAge()
                                    return -1;
                        } else{
                                    return 0;
                        }
            }
}


ComparatorExample.java:


package com.soft.examples;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;



import com.soft.model.Employee;
import com.soft.model.EmployeeAgeComparator;
import com.soft.model.EmployeeDepartmentComparator;
import com.soft.model.EmployeeMultipleFieldsComparator;
import com.soft.model.EmployeeNameComparator;

public class ComparatorExample {
public static void main(String[] args) {
List<Employee> list= new ArrayList<Employee>();
Employee e=new Employee();
e.setName("Danial Fritz");
e.setDepartment("Field Based Development");
e.setAge(36);
list.add(e);
e=new Employee();
e.setName("Denis Khoo");
e.setDepartment("Project Management");
e.setAge(30);
list.add(e);
e=new Employee();
e.setName("Joe Kum");
e.setDepartment("Adminstration");
e.setAge(40);
list.add(e);
e=new Employee();
e.setName("Anil Kumar");
e.setDepartment("Information Technology");
e.setAge(26);
list.add(e);
           
                       
System.out.println("************ Before Sorting ***********");
for (int i=0;i< list.size();i++){
System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
}
System.out.println("************ Name Sorting ***********");
Collections.sort(list, new EmployeeNameComparator());
for (int i=0;i< list.size();i++){
System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
}
System.out.println("************ Department Sorting ***********");
Collections.sort(list, new EmployeeDepartmentComparator());
for (int i=0;i< list.size();i++){
System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
}
System.out.println("************ Age Sorting ***********");
Collections.sort(list, new EmployeeAgeComparator());
for (int i=0;i< list.size();i++){
System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
}
}
}


This sorting can also be done through java.lang.Comparable, the implementation of which is given at
How to implement a java.lang.Comparable

The differences between java.util.Comparator and java.lang.Comparable are given at 





Differences between Comparator and Comparable

Following is a table of the differences between java.util.Comparator and  java.lang.Comparable  interfaces. If I have missed any point, please notify me of that.

The implementation of java.util.Comparator and java.lang.Comparable can be found at
Comparator and
Comparable respectively.



Comparator
Comparable
Package
Java.util
Java.lang
Method
public int compare (Object o1, Object o2)

returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second
public int compareTo(Object o)

returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object
Main Difference
Compares 2 objects provided to it.
Compares this object to the object given.


Used to implement natural ordering of objects. Implemented by String, Date and wrapper classes.


If any class implements Comparable interface then collection of that object either List or Array can be sorted automatically by using  Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.


Objects which implement Comparable in Java  can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.
Implementation
Normally, for a bean named Employee(String name, String Department, int Age), if we want to implement a name comparator, we need two classes: bean class(Employee) and comparator class as
public class Employee {} And
public class EmployeeNameComparator implements Comparator{}
For a bean name Employee(String name, String Department, int Age), if we want to implement a name comparable, we do not need to create a new class but instead we will implement it through the same Employee class as
public class Employee implements Comparable{}