How to simplify a null-safe compareTo() implementation?

前端 未结 17 2112
醉酒成梦
醉酒成梦 2020-11-28 18:03

I\'m implementing compareTo() method for a simple class such as this (to be able to use Collections.sort() and other goodies offered by the Java pl

17条回答
  •  生来不讨喜
    2020-11-28 18:33

    If you want a simple Hack:

    arrlist.sort((o1, o2) -> {
        if (o1.getName() == null) o1.setName("");
        if (o2.getName() == null) o2.setName("");
    
        return o1.getName().compareTo(o2.getName());
    })
    

    if you want put nulls to end of the list just change this in above metod

    return o2.getName().compareTo(o1.getName());
    

提交回复
热议问题