从列表中删除空元素。

28
List<String> list = new ArrayList<String>();
  list.add("One");
  list.add(null);
  list.add("Two!");
  list.add(null);
  list.add("Three");
  list.add(null);
  list.add("Four");
  list.add(null);

我有一个包含null元素的列表。是否有任何方法可以在不使用任何迭代的情况下从当前集合中删除null元素?


5
不需要你编写任何迭代代码吗?或者不需要编写任何代码?https://dev59.com/-m445IYBdhLWcg3wg6pm - LuckyLuke
10个回答

54
这应该能够工作:
list.removeAll(Collections.singleton(null));  

1
List.removeAll()的时间复杂度是n^2。就这样说吧。 - Hemanth
@Hermanth 对于那个单例,复杂度不是n*m吗,其中m==1 - kratenko

11

5

扩展 ArrayList 并覆盖 add()addAll() 方法,简单地不允许使用 null

或者你可以像这里所示使用 list.removeAll(null);,内部会迭代循环。


5
我不喜欢扩展这样的类,因为它可能会导致代码混乱。你还应该记住,你也可以使用ListIterator向列表中添加项目。 - Kai

3

看一下LambdaJ,它允许您在“不使用”循环的情况下操作集合。实际上,循环是在库内部实现的,但它确实很酷,并且简化了您的代码并使其更短。


2

虽然不够高效,但可以运行

while(list.remove(null));


1
当前的答案没有区分可变和不可变列表,我发现有很多方法缺失。随着 引入 List.of(..),这变得更加重要,尽管不能向其传递 null 元素。删除仍然是相关的(例如删除某个非空元素)。 不可变列表 一个不可变列表的例子是 Arrays.asList(..)(尽管元素仍然可以被替换,但不能添加/删除),或者已经提到的 List.of(..)。只要不能使用 List 方法添加/删除元素,它们就被认为是“不可变包装”。
List<String> immutableList = Arrays.asList("one", null, "two");
  • as of using the Stream#filter(Predicate) method:

    List<String> newList = immutableList.stream()
        .filter(Objects::nonNull)
        .collect(Collectors.toList());
    
  • For-each loop either with indices or the enhanced one is suitable (not only) for Java versions and lower.

    // note we need to create a mutable List to add the non-null elements
    List<String> newList = new ArrayList<>();
    for (String str: immutableList) {
        if (str != null) {
             newList.add(str);
        }
    }
    

可变列表

可变列表的一个例子是一个新的List接口实例,比如new ArrayList<>()或者new LinkedList<>()。它们是可变的,因此使用List#addList#addAll添加元素是可能的,也是常用的方法。

List<String> mutableList = new ArrayList<>(Arrays.asList("one", null, "two"));

以下列出了从List中删除所有null元素的方法。请注意,它会修改该列表。

  • List#removeIf(Predicate) as of

    mutableList.removeIf(Objects::isNull);
    
  • Iterator is a recommended way to remove elements from a List and is suitable (not only) for Java versions and lower

    Iterator<String> iterator = mutableList.iterator();
    while (iterator.hasNext()) {
        if (iterator.next() == null) {
            iterator.remove();
        }
    }
    
  • All the ways mentioned in the Immutable List section which always results in a new List.


0
如果您正在自己构建列表并且不确定值是否为null,您也可以使用CollectionUtils.addIgnoreNull(list,elementToAdd);。这将防止添加null元素。这仅适用于构建列表时。如果您从其他地方接收列表并希望在使用列表之前删除所有非null元素,则最好使用list.removeAll(Collections.singleton(null));

0
for (int i = 0; i <array.size(); i++) {
    for (int j = 0; j < array.size()-i-1; j++) {
        if (array.get(j) > array.get(j+i)){
            Integer t = array.get(j+i);
            array.set(j+i,array.get(j));
            array.set(j,t);
        }
    }
}

for(int i = array.size()-1; i >= 0; i--){

这是一个升序排列,那么这个问题的降序排列是什么?


问题应该在单独的帖子中提出。如果您想提出问题,请单击此处进行提问(http://stackoverflow.com/questions/ask)。回答问题意味着回答问题,而不是再提出另一个问题。 - Damodar Dahal

0

使用 google.common.:

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

public List<String> removeBlanks(List<String> list) {
    return Lists.newArrayList(Iterables.filter(list, new Predicate<String>() {

        @Override
        public boolean apply(String arg) {
            return StringUtils.isNotEmpty(arg);
        }
    }));
}

0
你可以使用Java Stream来过滤掉可空元素:
list.stream()
    .filter(Objects::nonNull)
    .collect(Collectors.toList())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接