CSV Input File.
EmployeeID,FirstName,LastName,Dept
1, John, Smith, Maintenance
1, John, Smith, Engineering
1, John, Smith, Transport
From the CSV file I read each line and create an employee object which is then stored into an ArrayList of Employee's.
Before sorting employee's:
employeeID='1', firstName='John', lastName='Smith', department='Maintenance'}
employeeID='1', firstName='John', lastName='Smith', department='Engineering'}
employeeID='1', firstName='John', lastName='Smith', department='Transport'}
Once file processing has finished, I move onto sorting the Employee’s.
Desired output after sort:
employeeID='1', firstName='John', lastName='Smith', department='Maintenance, Engineering, Transport'}
Using the For-Each with a nested For-Each, I compare the EmployeeID’s, if a match is found I append the dept of the duplicate to the original and remove the duplicate. Obviously as I’m modifying the list I’m iterating over I then get a ConcurrentModificationException.
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1042)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:996)
at com.gillott.csvtomap.CsvToMap.employeeSorter(CsvToMap.java:73)
at com.gillott.csvtomap.CsvToMap.main(CsvToMap.java:34)
I’ve seen online the advice for carrying out modification on the collection you are iterating over is to use the Iterator, I’ve implemented the Iterator but still get the same results, Is this because I’m using a nested For-Each? See For-Each implementation and For-Each with Iterator implementation.
For-Loop example:
for (Employee emp1: employees) { for (Employee emp2: employees){ if(emp1.getEmployeeID().equals(emp2.getEmployeeID())){ emp1.setdepartment(emp1.getdepartment() + ", " + emp2.getdepartment()); System.out.println("Duplicate found for Employee ID: " + emp1.getEmployeeID()); employees.remove(emp2); //CME Exception Throw here. } } }Iterator For-Loop example:
for (Iterator<Employee> employeeIterator1 = employees.iterator(); employeeIterator1.hasNext();) { Employee emp1 = employeeIterator1.next(); for (Iterator<Employee> employeeIterator2 = employees.iterator(); employeeIterator2.hasNext();){ Employee emp2 = employeeIterator2.next(); if(emp1.getEmployeeID().equals(emp2.getEmployeeID())){ emp1.setdepartment(emp1.getdepartment() + ", " + emp2.getdepartment()); System.out.println("Duplicate found for Employee ID: " + emp1.getEmployeeID()); employeeIterator1.remove(); } } }
My implementation of the Iterator could be incorrect, this is the first time using the Iterator directly.