Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java comparator properly?

If I have the following class:

public class Employee {
    private int empId;
    private String name;
    private int age;

    public Employee(int empId, String name, int age) {
        // set values on attributes
    }
    // getters & setters
}

How can I use comparator that compares by name, then age, then id?

like image 717
Sheehan Alam Avatar asked Aug 19 '11 04:08

Sheehan Alam


1 Answers

You need to implement it so that it orders by preferred elements. That is, you need to compare by name, then if that comparison is equal, compare by age, etc. An example is listed below:

public class EmployeeComparator implements Comparator<Employee> {

  @Override
  public int compare(Employee e1, Employee e2) {
    int nameDiff = e1.getName().compareTo(e2.getName());

    if(nameDiff != 0) {
      return nameDiff;
    }

    int ageDiff = e1.getAge() - e2.getAge();

    if(ageDiff != 0) {
      return ageDiff;
    }

    int idDiff = e1.getEmpId() - e2.getEmpId();

    return idDiff;
  }
}
like image 181
Bringer128 Avatar answered Sep 19 '22 01:09

Bringer128