Wednesday, 13 May 2020

Comparator Interface in java


-> Comparator used to sorting the object element by using multiple sorting sequence.

-> We can sort the elements on the basis of any data member, for example, rollno, name, age or anything else.

-> The comparator interface provide two methods like compare(Object obj1,Object obj2) and equals(Object obj).



1) compare(Object obj1,Object obj2) function

Its compares first object(obj1) and second object(obj2) and return int value

Syntax : public int compare(Object obj1,Object obj2)


positive integer = if the current object is greater than the specified object.
negative integer = if the current object is less than the specified object.
zero = if the current object is equal to the specified object.



2) equals(Object obj1) function

Its used to compare current object with specified object

Syntax : public boolean equals(Object obj1)




Example : Sorting by name and Emp id by using comparator

import java.util.*; 
import java.io.*;

// User - Defined Class

class Employee { 
int empid; 
String empname; 
int empage; 
Employee(int empid,String empname,int empage){ 
this.empid=empid; 
this.empname=empname; 
this.empage=empage; 

}


class sortByAge implements Comparator{
                         
public int compare(Object o1,Object o2){ 
Employee s1=(Employee)o1; 
Employee s2=(Employee)o2; 

if(s1.empage==s2.empage) 
return 0; 
else if(s1.empage>s2.empage) 
return 1; 
else 
return -1; 

   
}
 

class sortByName implements Comperator{
   
public int compare(Object o1,Object o2){ 
Employee s1=(Employee)o1; 
Employee s2=(Employee)o2; 

return s1.empname.compareTo(s2.empname);
   
}   
}


// Main Class



public class TestSort1{ 
public static void main(String args[]){ 
ArrayList<Employee> al=new ArrayList<Employee>(); 
al.add(new Employee(1,"Ajith",23)); 
al.add(new Employee(6,"Vijay",27)); 
al.add(new Employee(4,"Surya",21)); 
 
 
System.out.println("Sorting By Age"); 
Collections.sort(al, new sortByAge()); 
for(Employee st:al){ 
System.out.println(st.empid+" "+st.empname+" "+st.empage); 
}


System.out.println("Sorting By Name");
Collections.sort(al, new sortByName()); 
for(Employee st:al){ 
System.out.println(st.empid+" "+st.empname+" "+st.empage); 






Output

Sorting By Age

4 Surya 21
1 Ajith 23
6 Vijay 27


Sorting By Name

1 Ajith 23
4 Surya 21
6 Vijay 27

No comments:

Post a Comment