我试着像那样绕圈

// ArrayList tourists

for (Tourist t : tourists) {
    if (t != null) {     
        t.setId(idForm); 
    }   
}

但这并不好。谁能给我一个更好的解决办法?


一些有用的基准可以帮助你做出更好的决定:

While循环,For循环和迭代器性能测试


当前回答

我主要用这个:

list.removeAll(Collections.singleton(null));

但是在我学习了Java 8之后,我改用了这个:

List.removeIf(Objects::isNull);

其他回答

list.removeAll(Collections.singleton(null));

如果你在数组上使用它,它会抛出UnsupportedException。asList因为它给了你不可变的副本,所以它不能被修改。请参阅下面的代码。它创建可变副本,不会抛出任何异常。

public static String[] clean(final String[] v) {
    List<String> list = new ArrayList<String>(Arrays.asList(v));
    list.removeAll(Collections.singleton(null));
    return list.toArray(new String[list.size()]);
}

我摆弄了一下,发现trimToSize()似乎可以工作。我是在Android平台上工作,所以可能会有所不同。

List<String> colors = new ArrayList<>(
Arrays.asList("RED", null, "BLUE", null, "GREEN"));
// using removeIf() + Objects.isNull()
colors.removeIf(Objects::isNull);

有一种简单的方法可以从集合中删除所有空值。必须将包含null的集合作为参数传递给removeAll()方法

List s1=new ArrayList();
s1.add(null);

yourCollection.removeAll(s1);

我们可以使用迭代器for the same删除所有空值。

Iterator<Tourist> itr= tourists.iterator();
while(itr.hasNext()){
    if(itr.next() == null){
        itr.remove();
    }
}