1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
/* Remove an element from Collection using Java Iterator Example This Java Example shows how to remove an element from underlying Collection using Java Iterator's remove method. */ import java.util.Iterator; import java.util.ArrayList; public class RemoveElementThroughIteratorExample { public static void main(String[] args) { //create an ArrayList object ArrayList aList = new ArrayList(); //populate ArrayList object aList.add("1"); aList.add("2"); aList.add("3"); aList.add("4"); aList.add("5"); System.out.println("ArrayList before removal : "); for(int i=0; i< aList.size(); i++) System.out.println(aList.get(i)); //get an Iterator Iterator itr = aList.iterator(); //remove 2 from ArrayList using Iterator's remove method. String strElement = ""; while(itr.hasNext()){ /* Iterator's next method returns an Object so we need to cast it into appropriate class before using it. */ strElement = (String)itr.next(); if(strElement.equals("2")) { /* Remove an element using remove() method of Iterator Remove method removes an element from underlying collection and it may throw a UnsupportedOperationException if the remove operation is not supported. */ itr.remove(); break; } } System.out.println("ArrayList after removal : "); for(int i=0; i< aList.size(); i++) System.out.println(aList.get(i)); } } /* Output would be ArrayList before removal : 1 2 3 4 5 ArrayList after removal : 1 3 4 5 */ |
Add Comment