我试着像那样绕圈
// 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 the same删除所有空值。
Iterator<Tourist> itr= tourists.iterator();
while(itr.hasNext()){
if(itr.next() == null){
itr.remove();
}
}
其他回答
截至2015年,这是最好的方法(Java 8):
tourists.removeIf(Objects::isNull);
注意:对于固定大小的列表(例如使用Arrays.asList创建的列表),包括不可变列表,这段代码将抛出java.lang.UnsupportedOperationException。
我们可以使用迭代器for the same删除所有空值。
Iterator<Tourist> itr= tourists.iterator();
while(itr.hasNext()){
if(itr.next() == null){
itr.remove();
}
}
List<String> colors = new ArrayList<>(
Arrays.asList("RED", null, "BLUE", null, "GREEN"));
// using removeIf() + Objects.isNull()
colors.removeIf(Objects::isNull);
使用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 -流
这是从数组列表中删除默认空值的简单方法
tourists.removeAll(Arrays.asList(null));
从数组列表中删除字符串值“null”
tourists.removeAll(Arrays.asList("null"));