简体   繁体   中英

Java: Sorting objects in an ArrayList with conditions

I want to sort my ArrayList alphabetically. Therefore I wrote a sortEmployees method. In case my employees have the same name I'd like to sort them based on their salary, which means that the employee with the higher salary should be printed out first.

Well, I successfully managed to sort them alphabetically, but I don't know how I can compare, if employees have the same name and if that is the case, the employee with the higher salary shall be printed. Thanks.

ArrayList<Employee> employees = new ArrayList<Employee>();

public void sortEmployees(){
    Collections.sort(employees, (p1, p2) -> p1.name.compareTo(p2.name));
    for(Employee employee: employees){
        System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: "+employee.name + END_OF_LINE + "Salary: " + employee.grossSalary);
        System.out.println(""); // just an empty line
    }
}

Create an appropiate Comparator that will compare two items according to your desired criteria. Then use Collections.sort() on your ArrayList .

If at a later time you want to sort by different criteria, call Collections.sort() again with a different Comparator .

Reference: How to sort an ArrayList using multiple sorting criteria?

Just an advice for future questions, please google properly or search on stackoverflow for your problem before asking a new question. Most of the time such trivial questions have already been asked and answered.

I assume that you have the method equals to return whether two names are equal. You can define your Comparator as follows:

ArrayList<Employee> employees = new ArrayList<Employee>();

public void sortEmployees(){
  Collections.sort(employees, new Comparator<Employee>() {
    @Override 
    public int compare(Employee a, Employee b) {
      if (a.name.equals(b.name)) {
        return b.salary - a.salary;
      } else {
        return p1.name.compareTo(p2.name);
      }
    }
  });
  for(Employee employee: employees){
    System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: "+employee.name + END_OF_LINE + "Salary: " + employee.grossSalary);
    System.out.println(""); // just an empty line
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM