How to handle nulls when using Java collection sort

后端 未结 6 2105
离开以前
离开以前 2020-12-29 19:39

When using Collection.sort in Java what should I return when one of the inner objects is null

Example:

Collections.sort(list, new Comparator

        
6条回答
  •  既然无缘
    2020-12-29 20:17

    if comparing two property, attr1 natural order, attr2 reverse order, and attr2 can be null:

    datas.sort(comparing(Data::getAttr1, naturalOrder()).
            thenComparing(Data::getAttr2, nullsLast(reverseOrder())));
    

提交回复
热议问题