SomeName SomeFine
OtherName OtherFine
SomeOtherName SomeOtherFine
OtherName SomeOtherFine
SomeName OtherFine
I want to make a List<Map<String, Integer>>
so as to create a list of names and the total fines imposed upon them
The output I'm expecting (with reference to the example above) is something like this:
[SomeName=SomeFine+OtherFine, OtherName=OtherFine+SomeOtherFine, SomeOtherName=SomeOtherFine]
I tried using the following code, but it's giving me a ConcurrentModificationException
. Here's the code:
public List<Map<String, Integer>> calculateTotalFine(){
List<Map<String, Integer>> myMapList = new ArrayList<Map<String, Integer>>();
ListIterator<CrimeInfo> crimeIterator = list.listIterator();
while(crimeIterator.hasNext()){
String key = crimeIterator.next().getName();
Integer value = crimeIterator.next().getFine();
if(myMapList.isEmpty()){
Map<String, Integer> aMap = new HashMap<String, Integer>();
aMap.put(key, value);
myMapList.add(aMap);
}
else{
Iterator<Map<String, Integer>> mapIterator = myMapList.iterator();
while(mapIterator.hasNext()){
if(mapIterator.next().containsKey(key)){ //<-- Line no. 29
Integer newFine = mapIterator.next().get(key) + value;
mapIterator.remove();
Map<String, Integer> nMap = new HashMap<String, Integer>();
nMap.put(key, newFine);
myMapList.add(nMap);
}
else{
Map<String, Integer> newMap = new HashMap<String, Integer>();
newMap.put(key, value);
myMapList.add(newMap);
}
}
}
}
return myMapList;
}
Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) at java.util.ArrayList$Itr.next(ArrayList.java:851) at com.company.CoreLogic.calculateTotalFine(CoreLogic.java:29)
Can someone tell me where I'm going wrong?
The problem is that you're iterating over myMapList
, but modifying it while you're iterating:
myMapList.add(newMap);
I still haven't quite got to grips with what you're trying to do, but fundamentally you shouldn't be adding to the collection while you're iterating over it. One common approach is to create a new collection which you modify while you're iterating, and then (if necessary) perform a bulk modification of the original collection afterwards.
(As Titus says, you're also calling next()
twice within your loop... you need to take more care over how you use your iterators, and use an enhanced-for loop where possible.)
See more on this question at Stackoverflow