Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: sort list of objects by attribute without custom comparator

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); 
like image 309
Nabil Sham Avatar asked Nov 02 '15 21:11

Nabil Sham


People also ask

How do you sort a list of objects based on an attribute of the objects in Java 8?

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.

How do you sort an ArrayList of objects in Java 8?

– 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.


1 Answers

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)); 
like image 65
JB Nizet Avatar answered Sep 19 '22 17:09

JB Nizet