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

ListSortingLambdaJava 8

List Problem Overview


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);

List Solutions


Solution 1 - List

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));

Solution 2 - List

As a complement to @JB Nizet's answer, if your attr is nullable,

list.sort(Comparator.comparing(AnObject::getAttr));
 

may throw a NPE.

If you also want to sort null values, you can consider

    list.sort(Comparator.comparing(a -> a.attr, Comparator.nullsFirst(Comparator.naturalOrder())));

or

    list.sort(Comparator.comparing(a -> a.attr, Comparator.nullsLast(Comparator.naturalOrder())));

which will put nulls first or last.

Solution 3 - List

A null-safe option to JB Nizet's and Alex's answer above would be to do the following:

list.sort(Comparator.comparing(AnObject::getAttr, Comparator.nullsFirst(Comparator.naturalOrder())));

or

list.sort(Comparator.comparing(AnObject::getAttr, Comparator.nullsLast(Comparator.naturalOrder())));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNabil ShamView Question on Stackoverflow
Solution 1 - ListJB NizetView Answer on Stackoverflow
Solution 2 - ListAlexView Answer on Stackoverflow
Solution 3 - ListW.C.View Answer on Stackoverflow