ITPub博客

首页 > 数据库 > 数据库开发技术 > 删除List中null的N种方法--最后放大招

删除List中null的N种方法--最后放大招

原创 数据库开发技术 作者:FunTester 时间:2020-04-26 08:54:58 0 删除 编辑
  • 从List列表中删除null的不同方法:

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

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));
}
  • 请注意,在此处创建了一个可变列表。尝试从不可变列表中删除null将抛出java.lang.UnsupportedOperationException的错误。

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中的闭包


  • 郑重声明:“FunTester”首发,欢迎关注交流,禁止第三方转载。

技术类文章精选

无代码文章精选

原文作者:FunTester;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2019-07-07

  • 博文量
    1037
  • 访问量
    421262