In Java, How do you quicksort an ArrayList of objects in which the sorting field is multiple layers deep?

前端 未结 4 944
终归单人心
终归单人心 2021-02-10 13:51

Basically, I have a Container class called \"Employees\" which has in it an ArrayList. This ArrayList contains \"Employee\" objects, which in turn contain \"EmployeeData\" objec

4条回答
  •  萌比男神i
    2021-02-10 14:53

    You can make a comparator, something like:

    public class MyComparator implements Comparator
    {
      public int compare(Employee e1, Employee e2)
      {
        return e1.getData().getLast().compareTo(e2.getData().getLast());
      }
    }
    

    Then use it to sort the list.

    Collections.sort(myList, new MyComparator());
    

    Alternatively, you can use a TreeSet to sort on insertion using this comparator or make the Employee a comparable object to sort using Collections or a SortedSet.

    public class Employee implements Comperable
    {
      ...
      public int compareTo(Employee e)
      {
        return this.getData().getLast().compareTo(e.getData().getLast());
      }
      ...
    }
    

提交回复
热议问题