Difference between revisions of "Iterate a Collection and remove an item"

From CodeCodex

(Java)
 
(Ruby)
Line 85: Line 85:
 
}
 
}
 
</highlightsyntax>
 
</highlightsyntax>
 +
 +
===Ruby===
 +
<pre>
 +
list = ["Bart", "Lisa", "Marge", "Barney", "Homer", "Maggie"]
 +
list.delete_if{|s| s=="Barney"}
 +
p list                  #=> ["Bart", "Lisa", "Marge", "Homer", "Maggie"]
 +
</pre>
 +
 
[[Category:Java]]
 
[[Category:Java]]
 +
[[Category:Ruby]]
 +
[[Category:Arrays]]

Revision as of 12:01, 31 July 2010

Implementations

Java

You get an exception if while scanning a Collection, you decide to remove an item <highlightsyntax language="java122"> import java.util.ArrayList;

public class Simple {

 public static void main(String args[]) {
   ArrayList<String> list = new ArrayList<String>();
   list.add("Bart");
   list.add("Lisa");
   list.add("Marge");
   list.add("Barney");
   list.add("Homer");
   list.add("Maggie");
   for(String s: list)
   {
     if (s.equals("Barney")) {
       list.remove("Barney");
     }
     System.out.println(s);
   }
 }
 /*
   output :
       Bart
       Lisa
       Marge
       Barney
       Exception in thread "main" java.util.ConcurrentModificationException
         at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
         at java.util.AbstractList$Itr.next(Unknown Source)
         at com.rgagnon.howto.Simple.main(Simple.java:20)   
  */

} </highlightsyntax> The trick is to use an Iterator and remove the item with Iterator.remove() <highlightsyntax language="java122">

import java.util.ArrayList;

import java.util.Iterator;

public class Simple {

 public static void main(String args[]) {
   ArrayList<String> list = new ArrayList<String>();
   list.add("Bart");
   list.add("Lisa");
   list.add("Marge");
   list.add("Barney");
   list.add("Homer");
   list.add("Maggie");
   for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
     String s = iter.next();
     if (s.equals("Barney")) {
       iter.remove();
     }
     else {
       System.out.println(s);
     }
   }
   for(String s: list)
   {
     System.out.println(s);
   }
 }
 /*
   output :
       Bart
       Lisa
       Marge
       Homer
       Maggie
       Bart
       Lisa
       Marge
       Homer
       Maggie 
  */

} </highlightsyntax>

Ruby

list = ["Bart", "Lisa", "Marge", "Barney", "Homer", "Maggie"]
list.delete_if{|s| s=="Barney"}
p list                  #=> ["Bart", "Lisa", "Marge", "Homer", "Maggie"]