如何在使用Java集合排序时处理null [英] How to handle nulls when using Java collection sort

查看:2526
本文介绍了如何在使用Java集合排序时处理null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在Java中使用Collection.sort时,当其中一个内部对象为空时,我应该返回什么

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

示例:

Collections.sort(list, new Comparator<MyBean>() {
    public int compare(MyBean o1, MyBean o2) {
      return o2.getDate().compareTo(o1.getDate());
     } 

});

假设o2不是null,而是o2.getDate(),所以我应该返回1 -1或0当添加一个空验证?

Lets say o2 is not null but o2.getDate() it is, so should I return 1 or -1 or 0 when adding a null validation?

推荐答案

当然,这是你的选择。无论你写什么逻辑,它将定义排序规则。所以应该这里不是真正的正确的词。

Naturally, it's your choice. Whatever logic you write, it will define sorting rules. So 'should' isn't really the right word here.

如果你想让null出现在任何其他元素之前,这样的东西可以做

If you want null to appear before any other element, something like this could do

public int compare(MyBean o1, MyBean o2) {
    if (o1.getDate() == null) {
        return (o2.getDate() == null) ? 0 : -1;
    }
    if (o2.getDate() == null) {
        return 1;
    }
    return o2.getDate().compareTo(o1.getDate());
} 

这篇关于如何在使用Java集合排序时处理null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆