-1

I understand that when I try to modify (add in that case) the list I got ConcurrentModificationException, but what is the best solution to fix that?

for (Map.Entry<String, Child> entry : children.entrySet() {
     childEvent.child = entry.getValue();
     if (childEvent.getDate() != null && childEvent.getDate().equals(selectedDate)) {
         if(this.selectedDayevents.isEmpty()) {
             // List                                
             this.selectedDayevents.add(childEvent);
          }
         for (CareDay selectedCareDay : this.selectedDayevents) {
             // Here I have to combine data in some cases...
         }
     }  
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Sami
  • 2,311
  • 13
  • 46
  • 80
  • 2
    Collect the changes in an other `Map`, then use `Map.addAll` after you did loop over the entries. – Johannes Kuhn Oct 22 '19 at 06:11
  • But I need to add data inside the second for-loop to CareDay-objects so I think that it is not the solution to collect every changed object to third List,Map etc and then I have to loop those again (I think) – Sami Oct 22 '19 at 06:28
  • If you need to modify list during iterating - use this list `Iterator` to `add` and `remove` elements or create new list and add/remove to/from it. – Michał Krzywański Oct 22 '19 at 06:29
  • 1
    Please show the failing code in your [mcve]. Apparently the `add` statement you're showing is not the one that is failing? In that case you should remove it to make the example *minimal* , and please add the statement this *is* failing. Also please indent the code correctly - it's hardly possible to read it now. – Erwin Bolwidt Oct 22 '19 at 06:30

2 Answers2

0

One simple way around this problem is to iterate over a copy of the entry set:

for (Map.Entry<String, Child> entry : new HashSet<>(children.entrySet())) {
    // same code
}

If your map is not too big and you’re not doing it very often, you won’t notice a difference in performance.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
-1

If your requirement is to enable concurrent access to the collection, then you should explore java concurrency APIs and especially ConcurrentHashMap or ConcurrentSkipListMap for your case.

  • The OP didn't mention anything related to concurrent access. If you want to ask the OP a question, please use comments when you have enough reputation to do so. – Erwin Bolwidt Oct 22 '19 at 06:46
  • Erwin, my answer clearly starts with "If your requirement is...", hence the necessary conditional nature of the answer is explicitly mentioned. – Elisha Ebenezer Oct 22 '19 at 07:16