在列表的末尾放置null [英] Placing null at the end of the List

查看:169
本文介绍了在列表的末尾放置null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将空对象放在 List 的末尾。下面是我为此目的所做的一个例子:

I have a need to place null objects at the end of the List. Here is a sample what I have done for this purpose:

public static void main(String... args) {
    List<String> strings = Arrays.asList(new String[]{"A", null, "B"});

    for(String string : strings) {
        System.out.println(string);
    }

    System.out.println("==================");

    List<String> result = new ArrayList<String>();
    List<String> nullStrings = new ArrayList<String>();

    for(String string : strings) {
        if(string != null) {
            result.add(string);         
        } else {
            nullStrings.add(string);
        }
    }

    result.addAll(nullStrings);

    for(String string : result) {
        System.out.println(string);
    }
}



我期待着更高效,去做这个。是否可以在实际列表内部交换,以便将null节点放置在末尾,这样我不需要另外两个列表(nullStrings,result)和额外的迭代。

I am looking forward to a more efficient and intelligent way to do this. Is it possible to swap inside the actual list so that null node get placed at the end, so that I don't need the other two list(nullStrings, result) and extra iteration.

排序不适用于我的案例。这个示例代码我只是为了测试目的。其实我有一个不同类型的对象。

Sorting will not work for my case. This sample code I made just for testing purpose. Actually I have a different type of Object. Also Sorting will break the position.

说我有这个 null,Obj2,Obj1 ,如果做任何排序它可能发生 Obj1,Obj2,null 。但我需要 Obj2,Obj1,null

Say I have this null, Obj2, Obj1, if do anything like sorting it may happens Obj1, Obj2, null. But I need Obj2, Obj1, null.

推荐答案

它使用 Collections.sort 和自定义 Comparator

这里的比较代码:

@Override 
public int compare(String left, String right) {
 if (left == right) {
   return 0;
 }
 if (left == null) {
   return 1;
 }
 if (right == null) {
   return -1;
 }
 return 0;
 }

请注意,根据 Comparator 将不会重新排序。从 Collections.sort

Note that elements that have an equal value according to this Comparator won't be re-ordered. From Collections.sort:


:等于元素将不会作为排序的结果重新排序。

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

这篇关于在列表的末尾放置null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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