Monday, 10 February 2014

Comparator and Comparable

1.Sorting an Integer Array

Assume you have an integer array.
int a[]=new int[]{10,20,3,6,1};
To sort this Array the code is
?
1
2
3
4
5
int arr[]=new int[]{5,3,1,7,9};
Arrays.sort(arr);
 
 for(int num:arr)
        System.out.print(num);
O/p: 1 3 5 7 9
You may also choose various sorting algorithm like bubble,Quick sorts…

2.Sorting string Array

To sort the String Array,you may also use the above Arrays.sort()
?
1
2
3
4
5
6
7
String strArr[]=new String[]{"cat","dog","apple"};
Arrays.sort(strArr);
 
    for(String str:strArr)
    {
        System.out.println(str);
    }
O/p: apple cat dog

3.Sorting ArrayList

?
1
2
3
4
5
6
7
8
9
10
ArrayList name = new ArrayList();
name.add("Satya");
name.add("Raja");
name.add("Kiran");
name.add("Tech");
Collections.sort(name);
 
  for (String str : name) {
       System.out.println(str);
  }
Ouput:- 
Kiran Raja Satya Tech

Sorting User-defined class Object

Consider the Class Employee.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Employee
{
 String name;
 float salary;
 int empId;
 
 public Employee(String name, float salary, int empId)
 {
  this.name = name;
  this.salary = salary;
  this.empId = empId;
 }
}
Now Lets Create Employee Object Array
?
1
2
3
4
5
Employee emp1=new Employee("Raja",2500,110);
Employee emp2=new Employee("Nataraj",7000,205);
Employee emp3=new Employee("Satya",5000,117);
 
Employee empArr[]=new Employee[]{emp1,emp2,emp3} ;
How do you sort this Array?
If your write  Arrays.sort(empArr);  it will give you the following exeception
Exception in thread “main” java.lang.ClassCastException: Employee cannot be cast to java.lang.Comparable
If you Store emp1,emp2,emp3 in ArrayList and try Collections.sort(-),it will also give you the same problem.
ArrayList empList=new ArrayList();
empList.add(emp1);
empList.add(emp2);
empList.add(emp3);
Collections.sort(empList);
Here goes the complete Program
Comparator.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
class Employee {
  String name;
  float salary;
  int empId;
  public Employee(String name, float salary, int empId) {
    this.name = name;
    this.salary = salary;
    this.empId = empId;
  }
}
public class ComparatorDemo {
  public static void main(String args[]) {
    Employee emp1 = new Employee("Raja", 2500, 110);
    Employee emp2 = new Employee("Nataraj", 7000, 205);
    Employee emp3 = new Employee("Satya", 5000, 117);
    Employee empArr[] = new Employee[] { emp1, emp2, emp3 };
    Arrays.sort(empArr);//gives Exception
    ArrayList empList = new ArrayList();
    empList.add(emp1); empList.add(emp2);
    empList.add(emp3); Collections.sort(empList);// gives Exception
  }
}
ComparatorDemo.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
class Employee {
  String name;
  float salary;
  int empId;
  public Employee(String name, float salary, int empId) {
    this.name = name;
    this.salary = salary;
    this.empId = empId;
  }
}
public class ComparatorDemo {
  public static void main(String args[]) {
    Employee emp1 = new Employee("Raja", 2500, 110);
    Employee emp2 = new Employee("Nataraj", 7000, 205);
    Employee emp3 = new Employee("Satya", 5000, 117);
    Employee empArr[] = new Employee[] { emp1, emp2, emp3 };
    Arrays.sort(empArr);//gives Exception
    ArrayList empList = new ArrayList();
    empList.add(emp1);
    empList.add(emp2);
    empList.add(emp3);
 
    Collections.sort(empList);// gives Exception
  }
}
Why its giving Exception?
Employee object contains 3 properties,and it is confused,based on which property it has to compare,for sorting
Is it based on salary,or empId or Name?
This is the Actual need where you have to go for Comparator and Comparable.
Solution to the above problem
Use Comparator for this problem.
1.Your Employee class should implement Comparable interface
2.Override compareTo(Object obj) of Comparable interface
This method return type is integer.
For Ascending Order Sorting:
if(obj_param_value >current_obj_val) return -ve number
if(obj_param_value==current_obj_val) return 0
else return +ve number

For Descending Order Sorting
if(obj_param_value >current_obj_val) return +ve number
if(obj_param_value==current_obj_val) return 0
else return -ve number
Lets try to sort Employee based on empId
Modify the above program like this
ComparatorDemo.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
 
 class Employee implements Comparable {
 
    String name; 
    float salary;
    int empId;
 
   public Employee(String name, float salary, int empId){
     this.name = name;
     this.salary = salary;
     this.empId = empId;
   }
   public int compareTo(Object obj) {
     Employee emp2 = (Employee) obj;
     // ascending order return this.empId - emp2.empId;
     // descending order // return return this.empId-emp2.empId;
   }
 }
public class ComparatorDemo {
  public static void main(String args[]) {
    Employee emp1 = new Employee("Raja", 2500, 110);
    Employee emp2 = new Employee("Nataraj", 7000, 205);
    Employee emp3 = new Employee("Satya", 5000, 117);
    Employee empArr[] = new Employee[] { emp1, emp2,emp3 };
    Arrays.sort(empArr);
    System.out.println("Sorting using Array");
    for (int i = 0; i < empArr.length; i++) {
      Employee currEmp = empArr[i];
      System.out.println(currEmp.empId + "::" + 
                   currEmp.name);
    }
    ArrayList empList = new ArrayList();
    empList.add(emp1);
    empList.add(emp2);
    empList.add(emp3);
    Collections.sort(empList);
    System.out.println("Sorting using ArrayList");
    for (Employee emp : empList) {
      System.out.println(emp.empId + "::" + emp.name);
    }
  }
}
Output:-
 Sorting using Array
110::Raja
117::Satya
205::Nataraj
Sorting using ArrayList
110::Raja
117::Satya
205::Nataraj
Comparator:
Previously we saw,how to use Comparable to sort the Employee Object based on empId.
The Client May need flexible functionality where they can sort the Employee  based on anything(name or Id or phone…).
Here you have to use Comparator concept
Steps to Use Comparator
1.Create a Class(MyComparator) implementing Comparator interface,and override compare(-,-)
This method return type is integer.
For Ascending Order Sorting
if(object1 >object2) return +ve number
if(object1==object2) return 0
else return -ve number

For Descending Order Sorting
if(object1>object2) return -ve number
if(object1==object2) return 0
else return +ve number
2.Create the Object of MyComparator class,in your Employee Class(Who wants sorting)
   ComparatorEmpNameComparator= new MyComparator();[/code]
3.From your main class,pass Your Comparator Object name,while calling Collections.sort(-) or Arrays.sort()
 //This sorts the Object based on empName
Collections.sort(empList,Employee.EmpNameComparator);
//This sort the Object based on empId,as no 2nd parameter is given
Collections.sort(empList);
ComparatorDemo.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
                                                                                                                                                                                                                                                                                                                         import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
 
class MyComparator implements Comparator {
    public int compare(Employee emp1, Employee emp2) {
        // ascending order
        return emp1.name.toLowerCase().compareTo(emp2.name.toLowerCase());
        // descending order
        // return emp2.name.toLowerCase().compareTo(emp1.name.toLowerCase());
    }
}
class Employee implements Comparable {
    String name;
    float salary;
    int empId;
    public static Comparator EmpNameComparator = new MyComparator();
 
    public Employee(String name, float salary, int empId) {
        this.name = name;
        this.salary = salary;
        this.empId = empId;
    }
    public int compareTo(Object obj) {
        Employee emp2 = (Employee) obj;
        // ascending order
        return this.empId - emp2.empId;
        // descending order
        // return return this.empId-emp2.empId;
    }
}
public class ComparatorDemo {
    public static void main(String args[]) {
        Employee emp1 = new Employee("Raja", 2500, 110);
        Employee emp2 = new Employee("Nataraj", 7000, 205);
        Employee emp3 = new Employee("Satya", 5000, 117);
        Employee empArr[] = new Employee[] { emp1, emp2, emp3 };
        Arrays.sort(empArr);
        System.out.println("Sorting using Array");
        for (int i = 0; i < empArr.length; i++) {
            Employee currEmp = empArr[i];
            System.out.println(currEmp.empId + "::" + currEmp.name);
        }
        ArrayList empList = new ArrayList();
        empList.add(emp1);
        empList.add(emp2);
        empList.add(emp3);
        Collections.sort(empList);
        Collections.sort(empList, Employee.EmpNameComparator);
        System.out.println("Sorting using ArrayList");
        for (Employee emp : empList) {
            System.out.println(emp.empId + "::" + emp.name);
        }
    }
}
O/p:-
Sorting using Array
110::Raja
117::Satya
205::Nataraj
Sorting using ArrayList
205::Nataraj
110::Raja
117::Satya
 Note:
Array is sorted using Comparable here,as no second argument is given while calling sort(-) ArrayList is sorted using Comparator here,as 2nd argument is passed while calling sort(-); When to Use What
Use Comparator when you want to sort the Collections/Array based on a Single attribute of a Class(like empId)
Use Comparable when you may need to sort the collection/Array based on any attribute of a class(empId,or empName...).For Each Sort   (sortByName,SortById),Create a separate Comparable class
Comparator and Comparable
Both are used for Sorting Technique.However there are few differences between them
 1.Comparator interface is defined in java.util package.Comparable interface is defined in java.lang package.
2. Generally Comaparator should be used as an utility method to sort objects,which Comparable should be provided by default
3.Comparator interface has a methods public int compare(Object obj1,Object obj2)
   Comparable has one method public int compareTo(Object obj1)
Download Source Code Hope This Proved to be Valuable Article.
Any Bugs/Comments we Would like to hear from You.

No comments:

Post a Comment