java 删除集合中的空元素

java 删除集合中的空元素

方法一

注:下面代码中需要注意的是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]
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值