在查询过程中,可能会遇到查询出行数据都为null的情况,如下图所示:
我们可以采用以下的方法删除全为空的行数据
1. 使用原生Java删除空行
@Test
public void testRemoveNullElement() {
List list = new ArrayList<>(Arrays.asList(null, 1, null));
while (list.remove(null));
assertThat(list, hasSize(1));
}
debug结果:
2. 使用Apache Commons Collections删除空行
@Test
public void testRemoveNullElementByApache() {
List list = new ArrayList<>(Arrays.asList(null, 1, 2, null, 3, null));
CollectionUtils.filter(list, PredicateUtils.notNullPredicate());
assertThat(list, hasSize(3));
}
其中,filter的具体实现方法为:
public static boolean filter(final Iterable collection, final Predicate super T> predicate) {
boolean result = false;
if (collection != null && predicate != null) {
for (final Iterator it = collection.iterator(); it.hasNext();) {
if (!predicate.evaluate(it.next())) {
it.remove();
result = true;
}
}
}
return result;
}
3. 使用java8的lambdas表达式删除空行
@Test
public void testRemoveNullElementByLambdas() {
List list = new ArrayList<>(Arrays.asList(null, 1, 2, null, 3, null));
list.removeIf(Objects::isNull);
assertThat(list, hasSize(3));
}