List 删除 null 和 空值

1.removeIf()

        List<String> list = new ArrayList<>();
        list.add("zs");
        list.add(null);
        list.add("ls");
        list.add(null);
        list.add("");
        list.forEach(o -> System.out.println("删除前:" + o));
        list.removeIf(Objects::isNull);
        list.removeIf(o -> Objects.equals(o,"")); //同理也可以是其他值
        list.forEach(o -> System.out.println("删除后:" + o));

2.lambda

        List<String> list = new ArrayList<>();
        list.add("zs");
        list.add(null);
        list.add("ls");
        list.add(null);
        list.forEach(o -> System.out.println("删除前:" + o));
        List<String> collect = list.stream().filter(o -> o != null && !Objects.equals(o,"")).collect(Collectors.toList());
        collect.forEach(o -> System.out.println("删除后:" + o));

3.HuTool工具

        List<String> list = new ArrayList<>();
        list.add("zs");
        list.add(null);
        list.add("ls");
        list.add(null);
        list.forEach(o -> System.out.println("删除前:" + o));
        CollectionUtil.removeNull(list);//只能删除null
        CollectionUtil.removeEmpty(list);//能删除null和"" 删不了" "
        list.forEach(o -> System.out.println("删除后:" + o));

HuTool Maven 依赖


<dependency>
    <groupId>cn.hutoolgroupId>
    <artifactId>hutool-allartifactId>
    <version>5.8.16version>
dependency>

官方文档 https://doc.hutool.cn/pages/index/

4.CollectionUtils

        List<String> list = new ArrayList<>();
        list.add("zs");
        list.add(null);
        list.add("ls");
        list.add(null);
        list.add("");
        list.forEach(o -> System.out.println("删除前:" + o));
        CollectionUtils.filter(list,o -> !Objects.equals("",o) && o != null);
        list.forEach(o -> System.out.println("删除后:" + o));

Maven 依赖

        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-collections4artifactId>
            <version>4.4version>
        dependency>

5.迭代器

        List<String> list = new ArrayList<>();
        list.add("zs");
        list.add(null);
        list.add("ls");
        list.add(null);
        list.add("");
        list.forEach(o -> System.out.println("删除前:" + o));
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            if (next == null || (next != null && next.equals(""))) {
                iterator.remove();
            }
        }
        list.forEach(o -> System.out.println("删除后:" + o));

你可能感兴趣的:(list,java,collection,集合)