I am looking to implement a sort feature for my address book application.
I want to sort an ArrayList
. Contact
Ok, I know this was answered a long time ago... but, here's some new info:
Say the Contact class in question already has a defined natural ordering via implementing Comparable, but you want to override that ordering, say by name. Here's the modern way to do it:
List contacts = ...;
contacts.sort(Comparator.comparing(Contact::getName).reversed().thenComparing(Comparator.naturalOrder());
This way it will sort by name first (in reverse order), and then for name collisions it will fall back to the 'natural' ordering implemented by the Contact class itself.