如何在遍历时删除集合的数据

2023-09-06 面试专栏

# 1.普通的for循环,额外做--

public void listRemove() { 
    List<Student> students = this.getStudents(); 
    for (int i=0; i<students.size(); i++) { 
        if (students.get(i).getId()%3 == 0) { 
            Student student = students.get(i); 
            students.remove(student); 
            //做一次i--,避免漏删
            i--;
        } 
    } 
}

# 2.使用迭代器

public void iteratorRemove() { 
    List<Student> students = this.getStudents(); 
    Iterator<Student> stuIter = students.iterator(); 
    while (stuIter.hasNext()) { 
        Student student = stuIter.next(); 
        if (student.getId() % 2 == 0) {
            //这里要使用Iterator的remove方法移除当前对象,如果使用List的remove方法,则同样会出现ConcurrentModificationException 
        	stuIter.remove();
        } 
    }
} 

# 3.将原来的copy一份副本,遍历原来的list,然后删除副本(fail-safe)

public void copyRemove() {
    // 注意,这种方法的equals需要重写
	List<Student> students = this.getStudents();
    List<Student> studentsCopy = deepclone(students);
    for(Student stu : students) {
        if(needDel(stu)) {
            studentsCopy.remove(stu);
        }
    }
}

# 4. 使用并发安全的集合类

public void cowRemove() { 
    List<String> students = new CopyOnWriteArrayList<>(this.getStudents());
    for(Student stu : students) {
        if(needDel(stu)) {
            students.remove(stu);
        }
    }
}

# 5.通过Stream的过滤方法

因为Stream每次处理后都会生成一个新的Stream,不存在并发问题,所以Stream的filter也可以修改list集合

public List<String> streamRemove() { 
    List<String> students = this.getStudents();
    return students.stream()
        .filter(this::notNeedDel)
        .collect(Collectors.toList());
}

# 6.通过removeIf方法

removeIf() 方法用于删除所有满足特定条件的数组元素

arraylist.removeIf(this::needDel);
上次更新: 5 个月前