抛砖引玉,先抛砖,大招在最后。

Java 7 或更低版更低本

当使用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));
}

Java 8 或更高版本

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

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));
}

Google Guava

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));
}

Groovy 大招

    List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));

def re = list.findAll {
    it != null
}

assert re == ["A", "B"]

有兴趣可以读读Groovy 中的闭包


技术类文章精选

无代码文章精选


↙↙↙阅读原文可查看相关链接,并与作者交流