79

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);
1
  • 2
    Did you look the javadoc of the comparator class ? They added a bunch of methods (and you could directly do list1.sort(..) by the way). Commented Nov 2, 2015 at 21:23

3 Answers 3

184

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));
Sign up to request clarification or add additional context in comments.

6 Comments

What happens if attr is null?
Can u please share some link where I can read details about this. I want to sort using more than one attributes ( like first check atttr1, if attr1 of both obj are equal then check attr2)
@JBNizet does AnObject need to implement hascode,equals and compareTo?
No. The comparator will just call getAttr() on all the objects and compare the returned values.
Thank you for concise examples, though there is nothing wrong with data/tuple classes having exposed public fields. Thus "...clean if not using public fields" is not a universal rule.
|
31

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.

Comments

12

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.