我试着像那样绕圈
// 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循环和迭代器性能测试
当前回答
Objects类有一个非空谓词,可以与过滤器一起使用。
例如:
tourists.stream().filter(Objects::nonNull).collect(Collectors.toList());
其他回答
类似于@Lithium的答案,但不抛出“列表可能不包含类型null”错误:
list.removeAll(Collections.<T>singleton(null));
效率不高,但时间短
while(tourists.remove(null));
有一种简单的方法可以从集合中删除所有空值。必须将包含null的集合作为参数传递给removeAll()方法
List s1=new ArrayList();
s1.add(null);
yourCollection.removeAll(s1);
使用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 -流
Try:
tourists.removeAll(Collections.singleton(null));
阅读Java API。代码将为不可变列表抛出java.lang.UnsupportedOperationException(例如使用Arrays.asList创建的列表);更多细节请看这个答案。