java 8, Sort list of objects by attribute without custom comparator

后端 未结 3 1181
野的像风
野的像风 2020-11-28 09:18

What is the cleanest short way to get this done ?

 class AnObject{
     Long  attr;
 }

 List list; 

I know it can be done

相关标签:
3条回答
  • 2020-11-28 09:31

    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));
    
    0 讨论(0)
  • 2020-11-28 09:46

    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())));
    
    0 讨论(0)
  • 2020-11-28 09:50

    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.

    0 讨论(0)
提交回复
热议问题