我试着像那样绕圈
// 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循环和迭代器性能测试
当前回答
在Java 8中,可以使用流、并行流和removeIf方法以各种方式执行:
List<String> stringList = new ArrayList<>(Arrays.asList(null, "A", "B", null, "C", null));
List<String> listWithoutNulls1 = stringList.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList()); //[A,B,C]
List<String> listWithoutNulls2 = stringList.parallelStream()
.filter(Objects::nonNull)
.collect(Collectors.toList()); //[A,B,C]
stringList.removeIf(Objects::isNull); //[A,B,C]
并行流将利用可用的处理器,并将加快合理大小列表的处理速度。在使用流之前进行基准测试总是明智的。
其他回答
在Java 8中,可以使用流、并行流和removeIf方法以各种方式执行:
List<String> stringList = new ArrayList<>(Arrays.asList(null, "A", "B", null, "C", null));
List<String> listWithoutNulls1 = stringList.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList()); //[A,B,C]
List<String> listWithoutNulls2 = stringList.parallelStream()
.filter(Objects::nonNull)
.collect(Collectors.toList()); //[A,B,C]
stringList.removeIf(Objects::isNull); //[A,B,C]
并行流将利用可用的处理器,并将加快合理大小列表的处理速度。在使用流之前进行基准测试总是明智的。
Objects类有一个非空谓词,可以与过滤器一起使用。
例如:
tourists.stream().filter(Objects::nonNull).collect(Collectors.toList());
这是从数组列表中删除默认空值的简单方法
tourists.removeAll(Arrays.asList(null));
从数组列表中删除字符串值“null”
tourists.removeAll(Arrays.asList("null"));
效率不高,但时间短
while(tourists.remove(null));
for (Iterator<Tourist> itr = tourists.iterator(); itr.hasNext();) {
if (itr.next() == null) { itr.remove(); }
}