Java Comparator Event For Custom Sorting Employee Past Times Name, Historic Menstruum As Well As Salary

In this tutorial, nosotros volition run into Java Comparator event to variety an Employee object past times name, historic catamenia in addition to salary. In social club to variety Employee object on dissimilar criterion, nosotros postulate to practise multiple comparators e.g. NameComparator, AgeComparator and SalaryComparator, this is known equally custom sorting inwards Java. This is dissimilar in addition to thus natural ordering of object, provided past times compareTo() method of java.lang.Comparable interface. Though both compare() in addition to compareTo() method looks similar they are dissimilar inwards a feel that, sometime guide keep ane parameter, spell afterward guide keep 2 parameter. Former compare passed object to electrical flow object, on the other mitt compare() method compares 2 dissimilar object passed to it.

You tin practise this comparator equally nested static class, because they require access of someone members of class.

Once y'all practise these Comparator implementations, all y'all postulate to practise is to override compare() method accordingly e.g. inwards compare() method of NameComparator compare cite of 2 employee and render positive if cite of showtime employee is greater than second, in addition to render negative if cite of showtime employee is less than minute in addition to render zero if cite of both employees are equal.

By using Generics, y'all tin avoid casting of object into Employee inside compare() method, equally shown inwards event of this article. Once y'all guide keep your Comparator classes ready, y'all tin practise a bunch of employee in addition to variety them using whatsoever Comparator past times passing List of employees in addition to Comparator into Collections.sort(List, Comparator) method.

By the agency this Java event likewise implements equals(), hashcode(), compareTo() in addition to toString() method for Employee object, along amongst JUnit evidence for testing diverse Comparator implementation inwards file EmployeeTest.java.



Custom Sorting inwards Java using Comparator Example

 nosotros volition run into Java Comparator event to variety an Employee object past times cite Java Comparator Example for Custom Sorting Employee past times Name, Age in addition to Salary
Here is consummate code of creating dissimilar Comparator classes to compare objects on dissimilar attributes. In our event nosotros guide keep an Employee object, which has fields similar int id, String name, int salary, int age and Date field to correspond appointment of joining. Our requirement is to variety a List of employee based upon their name, age, salary in addition to appointment of joining. For this work nosotros guide keep 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. showtime ane compares cite of 2 employee object, minute compares their salary, 3rd compare their historic catamenia in addition to finally ane compare their age. When overriding compare() method, if y'all detect an object, which overrides compareTo() in addition to thus invoke that, for event for comparison String in addition to Date nosotros are invoking their compareTo() methods.

Files to run this Example
Employee.java
EmployeeTest.java

In social club to run this program, only re-create glue next 2 classes inwards 2 dissimilar Java root file. Then cite them according to cite of populace degree e.g. Employee.java in addition to EmployeeTest.java. You likewise postulate JUnit to run evidence file, which evidence the code y'all guide keep written for implementing Comparator in addition to overriding compare() method. You tin run it on Eclipse or ascendance prompt equally per your convenience. If y'all are non using JUnit in addition to thus y'all exactly pose the evidence code within top dog method of whatsoever degree in addition to 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 operate 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 likewise 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=" + cite + ", 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 degree to evidence sorting of Employee object on dissimilar parameters.
 * each evidence method volition evidence 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 event tutorial. We guide keep learned how to practise multiple Comparator in a degree for comparison object inwards dissimilar parameters. This allows y'all to variety object inwards whatsoever custom order, depending upon draw of piece of work concern requirement. You tin render custom Comparator as nested static class, because a Comparator is closely associated amongst the object it compare. This is ane of the genuine usage of nested static degree inwards Java. It's expert to render natural ordering of object via compareTo() method in addition to render additional compare() methods for custom sorting of object inwards Java. Always work Generics spell overriding compare(), this volition brand your programme equally straight off 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 variety an ArrayList inwards ascending in addition to descending social club inwards Java? (tutorial)
What is the departure betwixt ArrayList in addition to HashSet inwards Java? (answer)
What is the departure betwixt TreeMap in addition to TreeSet inwards Java? (answer)
What is the departure betwixt HashMap in addition to ConcurrentHashMap inwards Java? (answer)
The departure betwixt HashSet in addition to TreeSet inwards Java? (answer)
The departure betwixt ArrayList in addition to LinkedList inwards Java? (answer)
The departure betwixt Vector in addition to ArrayList inwards Java? (answer)

Thanks for reading this article thus far. If y'all similar this article in addition to thus delight portion amongst your friends in addition to colleagues. If y'all guide keep whatsoever questions or feedback in addition to thus delight drib a comment.

0 Response to "Java Comparator Event For Custom Sorting Employee Past Times Name, Historic Menstruum As Well As Salary"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel