0

I have two rich picklists whose selected item section or destination values must be mutually exclusive. I did this piece of code:-

    LinkedHashMap<String,Boolean> includeRatePlans = getCampaign().getDataPackages();
    LinkedHashMap<String, Boolean> excludeRatePlans = getCampaign().getSmsPackage();
    for (String excludeRatePlan : excludeRatePlans.keySet()){
        if(excludeRatePlans.get(excludeRatePlan)){
            for (String includeRatePlan : includeRatePlans.keySet()){
                if (includeRatePlans.get(includeRatePlan))
                    if (includeRatePlan.equals(excludeRatePlan)){
                        getCampaign().getSmsPackage().remove(excludeRatePlan);
                }
            }
        }
    }

But I am getting java.util.ConcurrentModificationException

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    Well yes, you're removing items from a collection while iterating over that collection. Either use the iterator directly, or build up a list of items to remove and then remove them all afterwards. – Jon Skeet Nov 24 '16 at 07:16

1 Answers1

1

You cannot modify the structure of a Map (i.e. adding or removing entries) while iterating over it with the enhanced for loop (and iterating over the keySet() makes no difference).

You can use an explicit iterator to remove entries :

LinkedHashMap<String,Boolean> includeRatePlans = getCampaign().getDataPackages();
LinkedHashMap<String, Boolean> excludeRatePlans = getCampaign().getSmsPackage();
Iterator<String> iter = excludeRatePlans.keySet().iterator();
while (iter.hasNext()) {
    String excludeRatePlan = iter.next();
    if(excludeRatePlans.get(excludeRatePlan)) {
        for (String includeRatePlan : includeRatePlans.keySet()){
            if (includeRatePlans.get(includeRatePlan))
                if (includeRatePlan.equals(excludeRatePlan)){
                    iter.remove();
            }
        }
    }
}

This will work since excludeRatePlans refers to the same Map as getCampaign().getSmsPackage() and removing an element from the KeySet of the Map also removes the corresponding entry from the Map.

Eran
  • 387,369
  • 54
  • 702
  • 768