我试着像那样绕圈
// 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(); }
}
其他回答
for (Iterator<Tourist> itr = tourists.iterator(); itr.hasNext();) {
if (itr.next() == null) { itr.remove(); }
}
我使用了流接口、流操作collect和一个helper方法来生成一个新列表。
tourists.stream().filter(this::isNotNull).collect(Collectors.toList());
private <T> boolean isNotNull(final T item) {
return item != null;
}
Objects类有一个非空谓词,可以与过滤器一起使用。
例如:
tourists.stream().filter(Objects::nonNull).collect(Collectors.toList());
Try:
tourists.removeAll(Collections.singleton(null));
阅读Java API。代码将为不可变列表抛出java.lang.UnsupportedOperationException(例如使用Arrays.asList创建的列表);更多细节请看这个答案。
我们可以使用迭代器for the same删除所有空值。
Iterator<Tourist> itr= tourists.iterator();
while(itr.hasNext()){
if(itr.next() == null){
itr.remove();
}
}