面对Comparator中的问题<>在Collections.sort中

时间:2014-08-19 12:27:01

标签: java comparator

您好以下是我的示例Java代码。我希望在我的应用程序中使用相同的逻辑。

/*Bean Class*/
public class TestingBean {
private Integer intOne;
private Integer intTwo;
//getters and setters
}

/**Main Class*/
public class FilterTesting {
public static void main(String[] args) {
    validateFilter();
}

public static void validateFilter() {
    List<TestingBean> testBeanList=new ArrayList<TestingBean>();

    TestingBean testingBean=new TestingBean();
    testingBean.setIntOne(1);
    testingBean.setIntTwo(1003);
    testBeanList.add(testingBean);

    TestingBean testingBean2=new TestingBean();
    testingBean2.setIntOne(2);
    testingBean2.setIntTwo(2002);
    testBeanList.add(testingBean2);

    TestingBean testingBean3=new TestingBean();
    testingBean3.setIntOne(null);
    testingBean3.setIntTwo(1);
    testBeanList.add(testingBean3);

    Collections.sort(testBeanList,
            new Comparator<TestingBean>() {
                @Override
                public int compare(final TestingBean obj1,
                        final TestingBean obj2) {
                    if(obj1.getIntOne()==null || obj2.getIntOne()==null){
                        return obj1.getIntTwo().compareTo(obj2.getIntTwo());
                    }
                    else{
                        return obj1.getIntOne().compareTo(obj2.getIntOne());
                    }
                }
            });
    for (TestingBean testBean : testBeanList) {
        System.out.println(testBean.getIntOne()+" : "+testBean.getIntTwo());
    }

}
}

当我运行此代码时,我得到输出为
null:1
1:1003
2:2002
 但我的要求是输出应该是
1:1003
2:2002
null:1
首先应该使用intOne对对象进行排序,如果intOne为null,则应使用intTwo进行排序。提前致谢。

1 个答案:

答案 0 :(得分:4)

此代码检查intOne null,并在检测到两个intTwo任何时跳转到比较intOne s是null

if(obj1.getIntOne()==null || obj2.getIntOne()==null){
    return obj1.getIntTwo().compareTo(obj2.getIntTwo());
}

这会产生你看到的效果。如果您希望获得您描述的效果,请按如下所示更改代码:

if(obj1.getIntOne()==null && obj2.getIntOne()==null) {
    return obj1.getIntTwo().compareTo(obj2.getIntTwo());
} else if(obj1.getIntOne()==null && obj2.getIntOne()!=null) {
    // Null is greater than any non-null number
    return 1;
} else if(obj1.getIntOne()!=null && obj2.getIntOne()==null) {
    // Non-null is smaller than null
    return -1;
} else {
    return obj1.getIntOne().compareTo(obj2.getIntOne());
}

仅当intTwointOne时,此更改才会使用null。如果其中只有一个是null,则null的值会被解释为非常大的数字。