0

I am trying delete a String that occurs 5 times in my List. This is what I've tried:

for(String obj : list1)
{
    if(new ArzList().countOccurrence(list1, obj ) == 5)
    {
        list2.add(obj);
        list1.removeAll(Collections.singleton(obj));                
    }
   else{
        list3.add(obj);
        list1.removeAll(Collections.singleton(obj));
   }
}

But I get java.util.ConcurrentModificationException each time.

How do I solve it?

user207421
  • 305,947
  • 44
  • 307
  • 483
Mamath Borus
  • 73
  • 1
  • 3
  • 12
  • i want list with no duplicate values. I can explain again. If consider one list1. i wan to divide into two list like list2 & 3. list2 contains no duplicate and each of it occurred 5 times in list1. the same way list3 may have no duplicate and each of it occurred less than 5 times in list. – Mamath Borus Feb 14 '15 at 07:31

3 Answers3

2

You shouldn't iterate and remove through the same list.

Create a copy of the original list. Iterate through the original list but remove items from the copy version. Return the duplicate(copy) version of the list.

kd0807
  • 660
  • 6
  • 14
0

You're not allowed to modify the data structure mid-way through an iterator.

You could just use a normal loop here:

for (int i = 0; i < list1.size(); i++) {
    String obj = list1.get(i);
    ...
}
mfjones
  • 739
  • 4
  • 16
  • why i did like this bcoz i want list with data which contains each datum with less tha 5 occurence in the list if so it will be removed totally. so give an other way to solve it – Mamath Borus Feb 14 '15 at 06:23
0

You can only safely delete an element during a loop from a collection using the Iterator.

Iterator<String> myIterator = list1.iterator();

while(myIterator.hasNext()) {
    //add logic to search list and delete element here
 }
Ojonugwa Jude Ochalifu
  • 26,627
  • 26
  • 120
  • 132