Using forEach and RemoveIf if used together will it cause ConcurrentModificationException?

I have three classes

 (With getters and Setters)

Student (Class)
   String studentName;
   int sid;
   List<Employee>

Employee (Class)
   String employeeName;
   int eid;
   List<Admin>

Admin (Class)
   String name;
   int adminId;

public class Testing {
public static void main(String arfs[]) {

    Admin admin = new Admin();
    Admin admin2 = new Admin();
    Employee employee = new Employee();
    Student student = new Student();

    List<Admin> adminList = new ArrayList<Admin>();
    List<Employee> empList = new ArrayList<>();

    admin.setName("AdminOne");
    admin.setAdminId(1);
    adminList.add(admin);

    admin2.setName("AdminTwo");
    admin2.setAdminId(2);
    adminList.add(admin2);

    employee.setEmployeeName("employeeOne");
    employee.setEid(4);
    employee.setAdmin(adminList);

    System.out.println("EMPLOYEE: "+employee.getAdmin());

    empList.add(employee);

    student.setStudentName("studentOne");
    student.setSid(9);
    student.setEmployee(empList);

    student.getEmployee().forEach(s -> {
        if(s.getEid()==4) {
            s.getAdmin().removeIf(p -> p.getName().equals("AdminTwo"));
        }
    });

    System.out.println("Student Name: "+student.getStudentName()+" EMP: "+student.getEmployee());


}
}

I am getting the output without any exceptions, but i would like to know is there any chance of getting “ConcurrentModificationException” from the above code…

When we iterate a collection and make modification in the same, we will get concurrent modification exception…

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

It is impossible to get ConcurrentModificationException with forEach or enchanced for because it is impossible also to modify the list.

In your case you iterate employeeList, but you modify adminList.