List集合实现边遍历边删除

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class StudentMethod {
    public static void main(String[] args) {
        Student student1 = new Student(1, "张三", "1991-01", 27);
        Student student2 = new Student(2, "李四", "1992-01", 15);
        Student student3 = new Student(3, "王五", "1993-01", 24);
        Student student4 = new Student(4, "赵六", "1994-01", 15);
        Student student5 = new Student(5, "李七", "1995-01", 29);
        Student student6 = new Student(6, "钱八", "1996-01", 18);
        Student student7 = new Student(7, "孙九", "1997-01", 25);
        Student student8 = new Student(8, "周八", "1998-01", 19);
        Student student9 = new Student(8, "周八", "1998-01", 19);

        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        list.add(student5);
        list.add(student6);
        list.add(student7);
        list.add(student8);
        list.add(student9);

        // List集合实现边遍历边删除
        /**
         * 第一种方法
         */
        Iterator<Student> iterator = list.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getName().equals("李四")) {
                iterator.remove();
            }
        }
        System.out.println("================第一种迭代器方式================");
        list.forEach(System.out::println);

        /**
         * 第二种方法
         */
        list.removeIf(m1 -> m1.getName().equals("周八"));
        System.out.println("================第二种JDK1.8新增的removeIf()方法方式================");
        list.forEach(System.out::println);
    }
}

class Student {
    private int id;
    private String name;
    private String birth;
    private int age;

    public Student() {

    }

    public Student(int id, String name, String birth, int age) {
        this.id = id;
        this.name = name;
        this.birth = birth;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBirth() {
        return birth;
    }

    public void setClassNo(String classNo) {
        this.birth = birth;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", birth='" + birth + '\'' +
                ", age=" + age +
                '}';
    }
}

 

posted @ 2022-04-29 12:28  蛋挞小子  阅读(654)  评论(0编辑  收藏  举报