-4

I Want to sort a List of employee in Java in which Boss name should appear first followed by other employeees in a Alphabetical order.

        Employee employee1 = new Employee();
        Employee employee2 = new Employee();
        Employee employee3 = new Employee();
        Employee employee4 = new Employee();
        employee2.setName("X1");
        employee2.setSalary("1000");

        employee1.setName("BOSS");
        employee1.setSalary("1000");

        employee3.setName("A2");
        employee3.setSalary("1000");

        employee4.setName("X3");
        employee4.setSalary("1000");

        List<Employee> lists = new ArrayList<Employee>();
        lists.add(employee1);
        lists.add(employee2);
        lists.add(employee3);
        lists.add(employee4);

After sorting the output should be 
BOSS
A2
X1
X3

1 Answers1

2

Try something to the effect of

lists.sort(new Comparator<Employee>() {
    @Override
    public int compare(Employee o1, Employee o2) {
        if (o1.getName().equals("BOSS")) { 
            if (o2.getName().equals("BOSS")) { return 0; } 
            else { return -1; }
        }
        else if (o2.getName().equals("BOSS")) { return 1; }
        else { return o1.getName().compareTo(o2.getName()); } 
    }
});

Here, we use an anonymous comparator class on Employee, where we first check whether either employee being compared is the "BOSS", and if so, force the value that would put the "BOSS" first. Otherwise, we do a simple compare on the names of the the employees.

Aaron Hammond
  • 617
  • 4
  • 9
  • This violates the Comparator contract, because compare(BOSS, BOSS) must return 0, not -1. – Durandal Dec 12 '14 at 20:09
  • But what if you have two BOSS'es? Either you need to fix `compare` to return 0 in that case, or we need to have them fight a duel until one is left standing. But I think a case where `compare(a,b)` and `compare(b,a)` both return -1 (or both return 1) violate the contract of the `Comparator` and could cause `sort` to throw an exception. – ajb Dec 12 '14 at 20:10
  • Actually, it could be a problem with only one `BOSS`, if the sort ever calls `compare` with the same object as both parameters. I don't know if it ever does, though. – ajb Dec 12 '14 at 20:11
  • 1
    @ajb thanks for the contract violation. updated my answer -- per the problem description (as I understand it), it shouldn't be an issue, but fault-tolerant code is good code. – Aaron Hammond Dec 12 '14 at 20:14
  • (The problem description might just be a subset of the actual data.) – David Conrad Dec 12 '14 at 20:30