方法一
注:下面代码中需要注意的是Arrays.asList
Arrays.asList创建的数据为定长集合,集合长度在操作时是不可以改变的,不能对集合进行增删操作。
如果操作会抛异常。具体可自行查看源代码。
List<Integer> list = new ArrayList<>(Arrays.asList(1, null,3, 4));
System.out.println(list);
list.removeAll(Collections.singleton(null));
System.out.println(list);
输出
[1, null, 3, 4]
[1, 3, 4]
方法二
其实和第一种方式一样 方法一的Collections.singleton(null)其实也是创建了一个集合,其中只有一个元素null
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, null,3, 4));
System.out.println(list1);
List nullList = new ArrayList();
nullList.add(null);
list1.removeAll(nullList);
System.out.println(list1);
输出
[1, null, 3, 4]
[1, 3, 4]
方法三
通过迭代器进行过滤
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, null,3, 4));
System.out.println(list1);
Iterator it = list1.iterator();
while (it.hasNext()) {
if (it.next() == null) {
it.remove();
}
}
System.out.println(list1);
输出
[1, null, 3, 4]
[1, 3, 4]