Search code examples
javasortingcomparatorcomparable

sort list of employees in Java in which Boss name should name appeas first followed by other employees in a alphabetical order


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

Solution

  • 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.