List
列表中删除null
的不同方法:抛砖引玉,先抛砖,大招在最后。
当使用Java 7
或更低版本时,我们可以使用以下结构从列表中删除所有空值:
@Test
public removeNull() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
list.removeAll(Collections.singleton(null));
assertThat(list, hasSize(2));
}
null
将抛出java.lang.UnsupportedOperationException
的错误。从Java 8
或更高版本,从List
列表中删除null
的方法非常直观且优雅:
@Test
public removeNull() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
list.removeIf(Objects::isNull);
assertThat(list, hasSize(2));
}
我们可以简单地使用removeIf()构造来删除所有空值。
如果我们不想更改现有列表,而是返回一个包含所有非空值的新列表,则可以:
@Test
public removeNull() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
List<String> newList = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
assertThat(list, hasSize(4));
assertThat(newList, hasSize(2));
}
Apache Commons CollectionUtils
类提供了一个filter
方法,该方法也可以解决我们的目的。传入的谓词将应用于列表中的所有元素:
@Test
public removeNull() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
CollectionUtils.filter(list, PredicateUtils.notNullPredicate());
assertThat(list, hasSize(2));
}
Guava
中的Iterables
类提供了removeIf()
方法,以帮助我们根据给定的谓词过滤值。
@Test
public removeNull() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
Iterables.removeIf(list, Predicates.isNull());
assertThat(list, hasSize(2));
}
另外,如果我们不想修改现有列表,Guava允许我们创建一个新的列表:
@Test
public removeNull() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
List<String> newList = new ArrayList<>(Iterables.filter(list, Predicates.notNull()));
assertThat(list, hasSize(4));
assertThat(newList, hasSize(2));
}
@Test
public removeNull() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
List<String> newList = new ArrayList<>(Iterables.filter(list, Predicates.notNull()));
assertThat(list, hasSize(4));
assertThat(newList, hasSize(2));
}
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
def re = list.findAll {
it != null
}
assert re == ["A", "B"]
有兴趣可以读读Groovy中的闭包