Friday, January 23, 2009

Java: Iterate ArrayList, Hashtable, TreeSet, LinkedHashMap

In the Java Code u can get All types of iterate all in one program. You can Iterate ArrayList, Hashtable, TreeSet, LinkedHashMap

ArrayList is an ordered Collection by Index

HashTable is Unorderd and Unsorted

TreeSet is a Sorted Collection in natural order

LinkedHashMap is Sorted Collection in insertion order




import java.util.*;

public class Iterators
{
public static void main(String[] args)
{
//Initilize ArrayList
ArrayList<String> arrayList = new ArrayList<String>();

//Initilize HashTable
Hashtable<String,Integer> hashTable = new Hashtable<String,Integer>();

//Initilize TreeSet
TreeSet<Integer> treeSet = new TreeSet<Integer>();

//Iterate LinkedHashMap
LinkedHashMap<Integer,String> linkedHashMap = new LinkedHashMap<Integer,String>();

//putting Values
for(int i=1;i<=10;i++)
{
arrayList.add("val"+i);
hashTable.put("keyHT"+i,i);
treeSet.add(i);
linkedHashMap.put(i,"keyLHM"+i);
}

//Iterating ArrayList
//ArrayList is an ordered Collection by Index
for(int i=0;i<arrayList.size();i++)
{
System.out.println(arrayList.get(i));
}

//Iterating HashTable
//HashTable is Unorderd and Unsorted
Enumeration<String> enu1 = hashTable.keys();
while(enu1.hasMoreElements())
{
String key=enu1.nextElement();
System.out.println(key+" "+hashTable.get(key));
}

//Iterating TreeSet
//TreeSet is a Sorted Collection in natural order
Iterator<Integer> itr1 = treeSet.iterator();
while(itr1.hasNext())
{
System.out.println(itr1.next());
}

//Iterating LinkedHashMap Key-Value pair
//LinkedHashMap is Sorted Collection in insertion order
Set<Integer> lSet= linkedHashMap.keySet();
Iterator<Integer> itr2 = lSet.iterator();
while(itr2.hasNext())
{
Integer key = itr2.next();
System.out.println(key+" "+linkedHashMap.get(key));
}

//Other Method to Iterate LinkedHashMap (Only Values)
Collection<String> col = linkedHashMap.values();
Iterator<String> itr3 = col.iterator();//obtain an Iterator for Collection
while(itr3.hasNext())//iterate through LinkedHashMap values iterator
{
System.out.println(itr3.next());
}

}
}

No comments:

Post a Comment