Mahatir Said
Mahatir Said

Reputation: 269

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
    }
}

Upvotes: 0

Views: 2469

Answers (2)

thinking_water
thinking_water

Reputation: 73

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
  }
}

Upvotes: 1

unrealsoul007
unrealsoul007

Reputation: 4087

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.

Upvotes: 2

Related Questions