JAVA——List中剔除空元素(null)的三种方法汇总
1、 list.removeAll(Collections.singleton(null));
List<String> list = new ArrayList<String>();
list.add("");
list.add("a");
list.add(null);
list.add(" ");
System.out.println(list);
System.out.println(list.size());
list.removeAll(Collections.singleton(null));
System.out.println(list);
System.out.println(list.size());
2、
List nullList = new ArrayList();
nullList.add(null);
list.removeAll(nullList);
List<String> list = new ArrayList<String>();
list.add("");
list.add("a");
list.add(null);
list.add(" ");
System.out.println(list);
System.out.println(list.size());
List l = new ArrayList();
l.add(null);
list.removeAll(l);
System.out.println(list);
System.out.println(list.size());
3、使用迭代器
List<String> list = new ArrayList<String>();
list.add("");
list.add("a");
list.add(null);
list.add(" ");
System.out.println(list);
System.out.println(list.size());
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
if(null == iterator.next()){
iterator.remove();
}
}
System.out.println(list);
System.out.println(list.size());