我试着像那样绕圈

// ArrayList tourists

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

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


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

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


当前回答

使用Java 8,可以使用stream()和filter()来实现这一点。

tourists = tourists.stream().filter(t -> t != null).collect(Collectors.toList())

or

tourists = tourists.stream().filter(Objects::nonNull).collect(Collectors.toList())

更多信息:Java 8 -流

其他回答

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

ImmutableList.copyOf(Iterables.filter(tourists, Predicates.notNull()))

类似于@Lithium的答案,但不抛出“列表可能不包含类型null”错误:

   list.removeAll(Collections.<T>singleton(null));
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()]);
}
List<String> colors = new ArrayList<>(
Arrays.asList("RED", null, "BLUE", null, "GREEN"));
// using removeIf() + Objects.isNull()
colors.removeIf(Objects::isNull);

效率不高,但时间短

while(tourists.remove(null));