I faced a problem once where I had to sort a list of unsorted objects
retrieved from a file (txt or csv file). I found a solution from stackoverflow :)
with the link: "How to sort List of objects by some property".
For example, I have a file name phonebook.txt that contains
9998887776 zen
1122334455 betty
1234567890 tom
I format these data first, then
store it in an ArrayList of type PhoneItem.
This array list contains the name and the phone
number unsorted.
Now, after playing (adding, removing, editing, etc)
the data I want to save it in the file sorted
by name alphabetically.
So in this case, betty comes first, tom
second and finally zen.
The end result would be:
1122334455 betty
1234567890 tom
9998887776 zen
This is where comparator is useful.
Using the name property to compare
objects we have a program that
goes like this.
1 2 3 4 5 6 7 8
// sort the phone list by alphabet order Collections.sort(this.PI_ARRAY_LIST, new Comparator<PhoneItem>() { @Override public int compare(PhoneItem o1, PhoneItem o2) { return o1.getName().compareToIgnoreCase(o2.getName()); }}); System.out.println(this.PI_ARRAY_LIST); // sorted
Or even better.
1 2
Collections.sort(li, (PhoneItem o1, PhoneItem o2) -> o1.getName().compareToIgnoreCase(o2.getName()));