I'm trying to find the first and newest object in an arraylist. These objects map directly to mongo documents.
The first object I can find easily by checking the _parentid field, which should be null, done, that's working.
The newest object is slightly trickier though, as it involves sorting timestamps(longs) and returning the latest.
The code I have is actually doing the job - proven by the console logs, but, I get an error on the last go of the for loop.
java.util.ConcurrentModificationException
Here is my code;
public String aggregateRecords(List <VehicleRegistration> records) {
VehicleRegistration parent;
VehicleRegistration latest;
//Parent = record without a parent id
for (Iterator<VehicleRegistration> iterator = records.iterator(); iterator.hasNext(); ) {
VehicleRegistration record = iterator.next(); <---errors here
if (record._parentid == null) {
parent = record;
System.out.println("parent="+parent);
iterator.remove();
}
//find latest child by timestamp
else {
records.sort(new Comparator<VehicleRegistration>() {
@Override
public int compare(VehicleRegistration v1, VehicleRegistration v2) {
return v1.timestamp.compareTo(v2.timestamp);
}
});
Collections.reverse(records);
System.out.println("sorted list="+records);
latest = records.get(0);
System.out.println("latest record="+latest);
}
}
//todo - merge together and return
return "this will be the aggregated record";
}