• java list移除null元素


    list<integer> ls = new ArrayList<integer>();
    list.add(1);
    list.add(2);
    list.add(null);
    list.add(3);
    list.add(null);
    list.add(4);

    如果只需移除第一个null, 那么直接

      ls.remove(null);

    如果要全部移除,可以这样

      list<integer> e = new ArrayList<integer>(1);

      e.add(null);

      ls.removeAll(e);

    这样做如果list元素类型不是integer,那么要改为相应类型。这样比较麻烦,可以写成一个Utils,但是还有一个更加简便的方法。

      ls.removeAll(Collections.singleton(null));

    Java 8或更高版本

    Java 8或更高版本,从List列表中删除null的方法非常直观且优雅:

    @Test
    public removeNull() {
        List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
        list.removeIf(Objects::isNull);
      
    System.out.println(list)
     }

    我们可以简单地使用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());
       System.out.println(newList)
        System.out.println(list)
    }
  • 相关阅读:
    Binary Tree Inorder Traversal
    Populating Next Right Pointers in Each Node
    Minimum Depth of Binary Tree
    Majority Element
    Excel Sheet Column Number
    Reverse Bits
    Happy Number
    House Robber
    Remove Linked List Elements
    Contains Duplicate
  • 原文地址:https://www.cnblogs.com/lyh233/p/14699766.html
Copyright © 2020-2023  润新知