java set 遍历删除_Java Collection在遍历中删除、合并元素

我的分词结果链表需要合并连续的数字和日期,所以需要熟悉一下Java Collection在遍历的过程中同时删除、合并元素的小trick。自己试验了一下,活用listIterator的previous()和next()方法就可以达到目的。

遍历中删除

数据集

List integerList = new LinkedList();

for (int i = 1; i <= 10; ++i)

{

integerList.add(i);

}

System.out.println(integerList);

也就是

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

遍历中删除所有奇数

// 遍历中删除所有奇数

ListIterator listIterator = integerList.listIterator();

while (listIterator.hasNext())

{

Integer next = listIterator.next();

if (next % 2 == 1)

{

listIterator.remove();

}

}

System.out.println(integerList);

输出:

[2, 4, 6, 8, 10]

遍历中合并

数据集

数据集接上面的输出

遍历中合并前后和为10的项

// 遍历中合并前后和为10的项

listIterator = integerList.listIterator();

Integer next = listIterator.next();

while (listIterator.hasNext())

{

Integer current = next;

next = listIterator.next();

if (current + next == 10)

{

// 此时listIterator指向6

listIterator.remove();

// 删除后listIterator还是指向6,但是其元素是无效的

listIterator.previous();

// 回退到4,将其合并为10

listIterator.set(10);

// 接下来会next到8

}

}

System.out.println(integerList);

输出:

[2, 10, 8, 10]

数据集

// 遍历中合并前后相等的项

integerList.clear();

for (int i = 1; i <= 5; ++i)

{

for (int j = 0; j 

{

integerList.add(i);

}

}

System.out.println(integerList);

也就是

[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5]

遍历中合并前后相等的项

listIterator = integerList.listIterator();

next = listIterator.next();

while (listIterator.hasNext())

{

Integer current = next;

next = listIterator.next();

if (current == next)

{

// 此时listIterator指向6

listIterator.remove();

// 删除后listIterator还是指向6,但是其元素是无效的

listIterator.previous();

// 回退到4,将其合并为10

listIterator.set(current + next);

// 接下来会next到8

}

}

System.out.println(integerList);

输出

[2, 1, 4, 2, 6, 3, 8, 4, 10, 5]

值得注意的是,上面并没有合并所有相同的项,因为在一句listIterator.set(current + next);之后,前后就不相等了。

本来想用两个迭代器去做,但是一个迭代器删除之后,会导致另一个迭代器失效,抛出ConcurrentModificationException异常,所以只能操作单个迭代器。

47fd5121b029d47900715e267fb6b2cd.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值