What is the cleanest short way to get this done ?
class AnObject{ Long attr; } List<AnObject> list;
I know it can be done with custom comparator for AnObject
. Isn't there something ready out of the box for such case?
Kind of like this:
Collections.sort(list, X.attr);
Java 8 introduced a sort method in the List interface which can use a comparator. The Comparator. comparing() method accepts a method reference which serves as the basis of the comparison. So we pass User::getCreatedOn to sort by the createdOn field.
– Use Collections. sort() method for sorting the ArrayList in-place, or Java 8 Stream. sorted() to return a new sorted ArrayList of Objects (the original List will not be modified). – For Descending order, just pass Collections.
Assuming you actually have a List<AnObject>
, all you need is
list.sort(Comparator.comparing(a -> a.attr));
If you make you code clean by not using public fields, but accessor methods, it becomes even cleaner:
list.sort(Comparator.comparing(AnObject::getAttr));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With