java删除list中所有null值

java删除list中所有null值

java Collection 框架提供简单解决方案,通过基本的while循环实现:

@Test
public void givenListContainsNulls_whenRemovingNullsWithPlainJava_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, null);
    while (list.remove(null));

    assertThat(list, hasSize(1));
}

remove方法当参数为null时,背后也是for循环,删除null 返回true,继续外层循环,直至全部null被删除。当然我们也可以使用removeAll方法

@Test
public void givenListContainsNulls_whenRemovingNullsWithPlainJavaAlternative_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, null);
    list.removeAll(Collections.singleton(null));

    assertThat(list, hasSize(1));
}

也可以通过Google Guava提供更实用的方法,使用predicte:

@Test
public void givenListContainsNulls_whenRemovingNullsWithGuavaV1_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, null);
    Iterables.removeIf(list, Predicates.isNull());

    assertThat(list, hasSize(1));
}

如果我们不想修改原list,可以创建一个新list

@Test
public void givenListContainsNulls_whenRemovingNullsWithGuavaV2_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, null, 2, 3);
    List<Integer> listWithoutNulls = Lists.newArrayList(
      Iterables.filter(list, Predicates.notNull()));

    assertThat(listWithoutNulls, hasSize(3));
}

Apache Commons Collections提供了简单的方式实现,使用类似函数式编程方式

@Test
public void givenListContainsNulls_whenRemovingNullsWithCommonsCollections_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
    CollectionUtils.filter(list, PredicateUtils.notNullPredicate());

    assertThat(list, hasSize(3));
}

java 8 lambda表达式解决方案,过滤list,且过滤过程可以是并行或串行:

@Test
public void givenListContainsNulls_whenFilteringParallel_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
    List<Integer> listWithoutNulls = list.parallelStream()
      .filter(Objects::nonNull)
      .collect(Collectors.toList());
}

@Test
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
    List<Integer> listWithoutNulls = list.stream()
      .filter(Objects::nonNull)
      .collect(Collectors.toList());
}

public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
    List<Integer> listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null);
    listWithoutNulls.removeIf(Objects::isNull);

    assertThat(listWithoutNulls, hasSize(3));
}



发布了10 篇原创文章 · 获赞 0 · 访问量 3854

猜你喜欢

转载自blog.csdn.net/weixin_43444783/article/details/93476391
今日推荐