我试着像那样绕圈
// ArrayList tourists
for (Tourist t : tourists) {
if (t != null) {
t.setId(idForm);
}
}
但这并不好。谁能给我一个更好的解决办法?
一些有用的基准可以帮助你做出更好的决定:
While循环,For循环和迭代器性能测试
我试着像那样绕圈
// ArrayList tourists
for (Tourist t : tourists) {
if (t != null) {
t.setId(idForm);
}
}
但这并不好。谁能给我一个更好的解决办法?
一些有用的基准可以帮助你做出更好的决定:
While循环,For循环和迭代器性能测试
当前回答
for (Iterator<Tourist> itr = tourists.iterator(); itr.hasNext();) {
if (itr.next() == null) { itr.remove(); }
}
其他回答
我主要用这个:
list.removeAll(Collections.singleton(null));
但是在我学习了Java 8之后,我改用了这个:
List.removeIf(Objects::isNull);
这是从数组列表中删除默认空值的简单方法
tourists.removeAll(Arrays.asList(null));
从数组列表中删除字符串值“null”
tourists.removeAll(Arrays.asList("null"));
for (Iterator<Tourist> itr = tourists.iterator(); itr.hasNext();) {
if (itr.next() == null) { itr.remove(); }
}
有一种简单的方法可以从集合中删除所有空值。必须将包含null的集合作为参数传递给removeAll()方法
List s1=new ArrayList();
s1.add(null);
yourCollection.removeAll(s1);
效率不高,但时间短
while(tourists.remove(null));