Java Comparator Event For Custom Sorting Employee Past Times Name, Historic Catamenia Too Salary
In this tutorial, nosotros volition encounter Java Comparator instance to kind an Employee object past times name, historic catamenia together with salary. In gild to kind Employee object on dissimilar criterion, nosotros require to do multiple comparators e.g. NameComparator, AgeComparator and SalaryComparator, this is known equally custom sorting inwards Java. This is dissimilar together with thence natural ordering of object, provided past times compareTo() method of java.lang.Comparable interface. Though both compare() together with compareTo() method looks similar they are dissimilar inwards a feel that, quondam receive got i parameter, piece afterwards receive got 2 parameter. Former compare passed object to electrical flow object, on the other manus compare() method compares 2 dissimilar object passed to it.
You tin do this comparator equally nested static class, because they require access of soul members of class.
Once y'all do these Comparator implementations, all y'all require to do is to override compare() method accordingly e.g. inwards compare() method of NameComparator compare lift of 2 employee and render positive if lift of get-go employee is greater than second, together with render negative if lift of get-go employee is less than minute together with render zero if lift of both employees are equal.
By using Generics, y'all tin avoid casting of object into Employee inside compare() method, equally shown inwards instance of this article. Once y'all receive got your Comparator classes ready, y'all tin do a bunch of employee together with kind them using whatever Comparator past times passing List of employees together with Comparator into Collections.sort(List, Comparator) method.
By the agency this Java instance equally good implements equals(), hashcode(), compareTo() together with toString() method for Employee object, along amongst JUnit seek for testing diverse Comparator implementation inwards file EmployeeTest.java.
Files to run this Example
Employee.java
EmployeeTest.java
In gild to run this program, precisely re-create glue next 2 classes inwards 2 dissimilar Java rootage file. Then lift them according to lift of populace cast e.g. Employee.java together with EmployeeTest.java. You equally good require JUnit to run seek file, which seek the code y'all receive got written for implementing Comparator together with overriding compare() method. You tin run it on Eclipse or ascendancy prompt equally per your convenience. If y'all are non using JUnit together with thence y'all precisely seat the seek code within principal method of whatever cast together with run it accordingly.
That's all on this Java Comparator instance tutorial. We receive got learned how to do multiple Comparator in a cast for comparison object inwards dissimilar parameters. This allows y'all to kind object inwards whatever custom order, depending upon work organisation requirement. You tin render custom Comparator as nested static class, because a Comparator is closely associated amongst the object it compare. This is i of the genuine usage of nested static cast inwards Java. It's practiced to render natural ordering of object via compareTo() method together with render additional compare() methods for custom sorting of object inwards Java. Always utilization Generics piece overriding compare(), this volition brand your plan equally similar a shot your compare() volition accept 2 Employee object, instead of 2 java.lang.Object parameters.
Further Learning
Java In-Depth: Become a Complete Java Engineer
tutorial)
How to kind an ArrayList inwards ascending together with descending gild inwards Java? (tutorial)
What is the divergence betwixt ArrayList together with HashSet inwards Java? (answer)
What is the divergence betwixt TreeMap together with TreeSet inwards Java? (answer)
What is the divergence betwixt HashMap together with ConcurrentHashMap inwards Java? (answer)
The divergence betwixt HashSet together with TreeSet inwards Java? (answer)
The divergence betwixt ArrayList together with LinkedList inwards Java? (answer)
The divergence betwixt Vector together with ArrayList inwards Java? (answer)
Thanks for reading this article thence far. If y'all similar this article together with thence delight part amongst your friends together with colleagues. If y'all receive got whatever questions or feedback together with thence delight drib a comment.
You tin do this comparator equally nested static class, because they require access of soul members of class.
Once y'all do these Comparator implementations, all y'all require to do is to override compare() method accordingly e.g. inwards compare() method of NameComparator compare lift of 2 employee and render positive if lift of get-go employee is greater than second, together with render negative if lift of get-go employee is less than minute together with render zero if lift of both employees are equal.
By using Generics, y'all tin avoid casting of object into Employee inside compare() method, equally shown inwards instance of this article. Once y'all receive got your Comparator classes ready, y'all tin do a bunch of employee together with kind them using whatever Comparator past times passing List of employees together with Comparator into Collections.sort(List, Comparator) method.
By the agency this Java instance equally good implements equals(), hashcode(), compareTo() together with toString() method for Employee object, along amongst JUnit seek for testing diverse Comparator implementation inwards file EmployeeTest.java.
Custom Sorting inwards Java using Comparator Example
Here is consummate code of creating dissimilar Comparator classes to compare objects on dissimilar attributes. In our instance nosotros receive got an Employee object, which has fields similar int id, String name, int salary, int age and Date field to stand upward for appointment of joining. Our requirement is to kind a List of employee based upon their name, age, salary together with appointment of joining. For this operate nosotros receive got created 4 dissimilar comparator classes namely NameComparator, AgeComparator, SalaryComparator and DOJComparator. All classes implements java.util.Comparator interface but their compare() method are overridden differently e.g. get-go i compares lift of 2 employee object, minute compares their salary, tertiary compare their historic catamenia together with lastly i compare their age. When overriding compare() method, if y'all abide by an object, which overrides compareTo() together with thence invoke that, for instance for comparison String together with Date nosotros are invoking their compareTo() methods.Files to run this Example
Employee.java
EmployeeTest.java
In gild to run this program, precisely re-create glue next 2 classes inwards 2 dissimilar Java rootage file. Then lift them according to lift of populace cast e.g. Employee.java together with EmployeeTest.java. You equally good require JUnit to run seek file, which seek the code y'all receive got written for implementing Comparator together with overriding compare() method. You tin run it on Eclipse or ascendancy prompt equally per your convenience. If y'all are non using JUnit together with thence y'all precisely seat the seek code within principal method of whatever cast together with run it accordingly.
Employee.java
===============
import java.util.Comparator;
import java.util.Date;
/**
*
* @author
*/
public class Employee implements Comparable<Employee>{
private int id;
private String name;
private int salary;
private int age;
private Date dateOfJoining;
public static final Comparator<Employee> AgeComparator = new Comparator<Employee>(){
@Override
public int compare(Employee o1, Employee o2) {
return o1.age - o2.age; // This volition piece of work because historic catamenia is positive integer
}
};
public static final Comparator<Employee> SalaryComparator = new Comparator<Employee>(){
@Override
public int compare(Employee o1, Employee o2) {
return o1.salary - o2.salary; // salary is equally good positive integer
}
};
public static final Comparator<Employee> NameComparator = new Comparator<Employee>(){
@Override
public int compare(Employee o1, Employee o2) {
return o1.name.compareTo(o2.name);
}
};
public static final Comparator<Employee> DOJComparator = new Comparator<Employee>(){
@Override
public int compare(Employee o1, Employee o2) {
return o1.dateOfJoining.compareTo(o2.dateOfJoining);
}
};
public Employee(int id, String name, int salary, int age, Date dateOfJoining) {
this.id = id;
this.name = name;
this.salary = salary;
this.age = age;
this.dateOfJoining = dateOfJoining;
}
@Override
public String toString() {
return "Employee{" + "id=" + id + ", name=" + lift + ", salary=" + salary + ", age=" + historic catamenia + ", dateOfJoining=" + dateOfJoining + '}';
}
@Override
public int compareTo(Employee o) {
return this.id - o.id;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Employee other = (Employee) obj;
if (this.id != other.id) {
return false;
}
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
if (this.salary != other.salary) {
return false;
}
if (this.age != other.age) {
return false;
}
if (this.dateOfJoining != other.dateOfJoining && (this.dateOfJoining == null || !this.dateOfJoining.equals(other.dateOfJoining))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.id;
hash = 47 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 47 * hash + this.salary;
hash = 47 * hash + this.age;
hash = 47 * hash + (this.dateOfJoining != null ? this.dateOfJoining.hashCode() : 0);
return hash;
}
}
EmployeeTest.java
==================
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Test cast to seek sorting of Employee object on dissimilar parameters.
* each seek method volition seek each Comparator implementation.
* @author http://javarevisited.blogpot.com
*/
public class EmployeeTest {
@Test
public void testEmployeeSorting(){
Employee e1 = new Employee(1, "A", 1000, 32, new Date(2011, 10, 1));
Employee e2 = new Employee(2, "AB", 1300, 22, new Date(2012, 10, 1));
Employee e3 = new Employee(3, "B", 10, 42, new Date(2010, 11, 3));
Employee e4 = new Employee(4, "CD", 100, 23, new Date(2011, 10, 1));
Employee e5 = new Employee(5, "AAA", 1200, 26, new Date(2011, 10, 1));
List<Employee> listOfEmployees = new ArrayList<Employee>();
listOfEmployees.add(e1);
listOfEmployees.add(e2);
listOfEmployees.add(e3);
listOfEmployees.add(e4);
listOfEmployees.add(e5);
System.out.println("Unsorted List : " + listOfEmployees);
Collections.sort(listOfEmployees); //Sorting past times natural order
assertEquals(e1, listOfEmployees.get(0));
assertEquals(e5, listOfEmployees.get(4));
Collections.sort(listOfEmployees, Employee.NameComparator);
assertEquals(e1, listOfEmployees.get(0));
assertEquals(e4, listOfEmployees.get(4));
Collections.sort(listOfEmployees, Employee.AgeComparator);
assertEquals(e2, listOfEmployees.get(0));
assertEquals(e3, listOfEmployees.get(4));
Collections.sort(listOfEmployees, Employee.SalaryComparator);
assertEquals(e3, listOfEmployees.get(0));
assertEquals(e2, listOfEmployees.get(4));
Collections.sort(listOfEmployees, Employee.DOJComparator);
assertEquals(e3, listOfEmployees.get(0));
assertEquals(e2, listOfEmployees.get(4));
}
}
That's all on this Java Comparator instance tutorial. We receive got learned how to do multiple Comparator in a cast for comparison object inwards dissimilar parameters. This allows y'all to kind object inwards whatever custom order, depending upon work organisation requirement. You tin render custom Comparator as nested static class, because a Comparator is closely associated amongst the object it compare. This is i of the genuine usage of nested static cast inwards Java. It's practiced to render natural ordering of object via compareTo() method together with render additional compare() methods for custom sorting of object inwards Java. Always utilization Generics piece overriding compare(), this volition brand your plan equally similar a shot your compare() volition accept 2 Employee object, instead of 2 java.lang.Object parameters.
Further Learning
Java In-Depth: Become a Complete Java Engineer
tutorial)
How to kind an ArrayList inwards ascending together with descending gild inwards Java? (tutorial)
What is the divergence betwixt ArrayList together with HashSet inwards Java? (answer)
What is the divergence betwixt TreeMap together with TreeSet inwards Java? (answer)
What is the divergence betwixt HashMap together with ConcurrentHashMap inwards Java? (answer)
The divergence betwixt HashSet together with TreeSet inwards Java? (answer)
The divergence betwixt ArrayList together with LinkedList inwards Java? (answer)
The divergence betwixt Vector together with ArrayList inwards Java? (answer)
Thanks for reading this article thence far. If y'all similar this article together with thence delight part amongst your friends together with colleagues. If y'all receive got whatever questions or feedback together with thence delight drib a comment.

Komentar
Posting Komentar