Friday, October 31, 2014

Java Iterator Pro



Iterate through elements Java Vector using Iterator

import java.util.Vector;
import java.util.Iterator;
public class IterateThroughVectorUsingIteratorExample
{
public static void main(String[] args)
{
Vector v = new Vector();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
Iterator itr = v.iterator();
System.out.println("Iterating through Vector elements...");
while(itr.hasNext())
System.out.println(itr.next());
   }
}

Iterate through elements Java Array List using Iterator

import java.util.ArrayList;
import java.util.Iterator;
public class IterateThroughArrayListUsingIteratorExample
{
public static void main(String[] args) 
{
ArrayList arrayList = new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
Iterator itr = arrayList.iterator();
System.out.println("Iterating through ArrayList elements...");
while(itr.hasNext())
System.out.println(itr.next());
   }
}

Iterate through elements of Java Linked List using Iterator

import java.util.Iterator;
import java.util.LinkedList;
public class IterateThroughLinkedListUsingIteratorExample
{
public static void main(String[] args)
 {
LinkedList lList = new LinkedList();
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
Iterator itr = lList.iterator();
System.out.println("Iterating through elements of Java LinkedList...");
System.out.println("LinkedList contains : ");
while(itr.hasNext())
{
System.out.println(itr.next());
     }
  }
}

Remove an element from Collection using Java Iterator

import java.util.Iterator;
import java.util.ArrayList;
public class RemoveElementThroughIteratorExample
{
public static void main(String[] args)
{
ArrayList aList = new ArrayList();
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));   Iterator itr = aList.iterator();
String strElement = "";
while(itr.hasNext())
{
strElement = (String)itr.next();
if(strElement.equals("2"))
{
itr.remove();
break;
}
}
System.out.println("ArrayList after removal : ");
for(int i=0; i< aList.size(); i++)
System.out.println(aList.get(i));
   }
}

No comments:

Post a Comment