标签:java 遍历 over nbsp lambda表达式 mamicode add 删除 string
一、首先list遍历方法有那么几种:使用for循环、iterator、还有就是lambda表达式循环
1、首先创建一个测试类
class User2{ Integer id; String name; public User2(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User2{" + "id=" + id + ", name=‘" + name + ‘\‘‘ + ‘}‘; } }
2、第一种遍历循环:fori循环
@Test public void forTest(){ List<User2> list = new ArrayList<>(); list.add(new User2(1,"张三1")); list.add(new User2(2,"张三2")); list.add(new User2(3,"张三3")); list.add(new User2(5,"张三4")); list.add(new User2(5,"张三5")); list.add(new User2(6,"张三6")); list.add(new User2(7,"张三7")); for (int i = 0; i < list.size(); i++) { User2 user = list.get(i); if(list.get(i).getId() == 5){ list.remove(user); } } System.out.println(list); }
执行结果为:
[User2{id=1, name=‘张三1‘}, User2{id=2, name=‘张三2‘}, User2{id=3, name=‘张三3‘}, User2{id=5, name=‘张三5‘}, User2{id=6, name=‘张三6‘}, User2{id=7, name=‘张三7‘}]
很明显,并没有达到我们预期的效果,因为下标是固定死的自增,但list的大小在随着删除元素不停的减小,并且后面的元素往前移了1位,所以后面的元素遍历不到。阿里巴巴编码规范中也有说明
3、第二种:foreach循环
@Test public void forTest(){ List<User2> list = new ArrayList<>(); list.add(new User2(1,"张三1")); list.add(new User2(2,"张三2")); list.add(new User2(3,"张三3")); list.add(new User2(5,"张三4")); list.add(new User2(5,"张三5")); list.add(new User2(6,"张三6")); list.add(new User2(7,"张三7")); for (User2 user : list) { if(user.getId() == 5){ list.remove(user); } } System.out.println(list); }
报出异常:java.util.ConcurrentModificationException,关于这个异常的原因,看了很多文章,基本上解释如下:ArrayList的父类AbstarctList中有一个域modCount,每次对集合进行修改(增添、删除元素)时modCount都会+1。
4、使用lambda表达式,这种方法是可以使用的,但是使用lambda先循环在从中删除的方式是不可行的,原因和foreach方法一样
@Test public void forTest(){ List<User2> list = new ArrayList<>(); list.add(new User2(1,"张三1")); list.add(new User2(2,"张三2")); list.add(new User2(3,"张三3")); list.add(new User2(5,"张三4")); list.add(new User2(5,"张三5")); list.add(new User2(6,"张三6")); list.add(new User2(7,"张三7")); //可行 list.removeIf(user -> user.getId() == 5); //不可行 list.forEach(user2 -> { if(user2.getId() == 5){ list.remove(user2); } }); System.out.println(list); }
5、使用迭代器删除也是可以的
@Test public void forTest(){ List<User2> list = new ArrayList<>(); list.add(new User2(1,"张三1")); list.add(new User2(2,"张三2")); list.add(new User2(3,"张三3")); list.add(new User2(5,"张三4")); list.add(new User2(5,"张三5")); list.add(new User2(6,"张三6")); list.add(new User2(7,"张三7")); Iterator iterator = list.iterator(); while (iterator.hasNext()){ User2 user2 = (User2) iterator.next(); if(user2.getId() == 5){ iterator.remove(); } } System.out.println(list); }
执行结果:
[User2{id=1, name=‘张三1‘}, User2{id=2, name=‘张三2‘}, User2{id=3, name=‘张三3‘}, User2{id=5, name=‘张三5‘}, User2{id=6, name=
java 删除list中符合条件的对象(几种方法,避免入坑)
标签:java 遍历 over nbsp lambda表达式 mamicode add 删除 string
原文地址:https://www.cnblogs.com/romantic-321/p/14717843.html