How to handle nulls when using Java collection sort

后端 未结 6 2100
离开以前
离开以前 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:20

    In Java 8 you can also use nullsFirst():

    Comparator.nullsFirst(Date::compareTo).compare(dateOne, dateTwo);
    

    Or nullsLast():

    Comparator.nullsLast(Date::compareTo).compare(dateOne, dateTwo);
    

    These methods will either sort null to the beginning or to the end. There is no wrong or right whether you consider null bigger or smaller than another objects. This is totally up to you, as others stated already.

提交回复
热议问题