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

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

问题描述

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

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 不为空,但 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 集合排序时如何处理空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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