我试着像那样绕圈

// ArrayList tourists

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

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


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

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


当前回答

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

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

yourCollection.removeAll(s1);

其他回答

在Java 8中,可以使用流、并行流和removeIf方法以各种方式执行:

List<String> stringList = new ArrayList<>(Arrays.asList(null, "A", "B", null, "C", null));
List<String> listWithoutNulls1 = stringList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList()); //[A,B,C]
List<String> listWithoutNulls2 = stringList.parallelStream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList()); //[A,B,C]
stringList.removeIf(Objects::isNull); //[A,B,C]

并行流将利用可用的处理器,并将加快合理大小列表的处理速度。在使用流之前进行基准测试总是明智的。

效率不高,但时间短

while(tourists.remove(null));

Try:

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

阅读Java API。代码将为不可变列表抛出java.lang.UnsupportedOperationException(例如使用Arrays.asList创建的列表);更多细节请看这个答案。

如果你更喜欢不可变的数据对象,或者你不想破坏输入列表,你可以使用Guava的谓词。

ImmutableList.copyOf(Iterables.filter(tourists, Predicates.notNull()))
List<String> colors = new ArrayList<>(
Arrays.asList("RED", null, "BLUE", null, "GREEN"));
// using removeIf() + Objects.isNull()
colors.removeIf(Objects::isNull);