-2

I have an ArrayList of custom Java users that I need to sort. An User is simply a user in the system. However the user has many attributes. To create the initial list, these are the calls necessary:

ArrayList<Identity> contractors = (ArrayList<Identity>) resource.searchUsers(null, null, null, null, null, null, null, null, "Contractor", "active");

The object resource is also a custom Java class with the necessary database calls to return the array list of contractors.

My question is how would I go about sorting an array list of complicated items such as this with many different attributes?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
PT_C
  • 1,178
  • 5
  • 24
  • 57
  • 3
    The same way you'd sort an ArrayList of simple items. You can sort via `Collections.sort(myArrayList)`. The key is in the Comparator's `compare(...)` or Comparable's `compareTo(...)` method that you write. What have you tried? How is it not working? – Hovercraft Full Of Eels Nov 20 '14 at 19:55
  • Collections.sort(List) T extends Comparable – Kamil.H Nov 20 '14 at 19:56
  • I have tried creating a subList of the items but didn't know how to compare two items of the list. – PT_C Nov 20 '14 at 19:56

1 Answers1

2

There are 2 steps:

class CustomComparator implements Comparator<Identity> {
    @Override
    public int compare(Identitya, Identityb) {
        return // compare here all values
    }
}

Then use this comparator with sort function:

Collections.sort(peps, new CustomComparator() );

If you are interested in sorting, you must write the login inside comparator.

This solution is cleaner than implementing Comparable by your DTO, because you can create and use many comparators, acording to your needs. And your code is clean, easy to test.

Usefull link here:

http://www.tutorialspoint.com/java/java_using_comparator.htm

Beri
  • 11,470
  • 4
  • 35
  • 57