Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop on list with remove [duplicate]

    for (String fruit : list)     {         if("banane".equals(fruit))             list.remove(fruit);         System.out.println(fruit);     } 

Here a loop with remove instruction. At execution time, I get some ConcurrentModificationException, below the console output:

Exception in thread "main" java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449) at java.util.AbstractList$Itr.next(AbstractList.java:420) at Boucle.main(Boucle.java:14) abricot banane 

Question: How to remove some element with a loop?

like image 511
enguerran Avatar asked Dec 17 '09 11:12

enguerran


People also ask

How remove duplicates from a list in loop?

You can make use of a for-loop that we will traverse the list of items to remove duplicates. The method unique() from Numpy module can help us remove duplicate from the list given. The Pandas module has a unique() method that will give us the unique elements from the list given.

How do you remove duplicates from a single loop array?

The only way to remove duplicates with a single loop is with a hashset or equivalent. Sorting the list first also works, but technically sorting involves many loops. calloc a status bit array, check if previously found and mark off. If the next value exceeds the range, realloc and clear the new elements.

How do you remove duplicates from a list while keeping the same order of the elements?

If you want to preserve the order while you remove duplicate elements from List in Python, you can use the OrderedDict class from the collections module. More specifically, we can use OrderedDict. fromkeys(list) to obtain a dictionary having duplicate elements removed, while still maintaining order.


1 Answers

You need to use the iterator directly, and remove the item via that iterator.

for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {     String fruit = iterator.next();     if ("banane".equals(fruit)) {         iterator.remove();     }     System.out.println(fruit); } 
like image 144
Jon Skeet Avatar answered Oct 05 '22 12:10

Jon Skeet