Friday, August 21, 2009

Java : Sorting and Randomly iterating Hashtable

As Hashtable is unordered and unsorted by default many time its required to sort it or randomly access its data. Same applicable with LinkedHashMap, TreeMap, HashMap.

In below example ArrayList is used to sort and shuffle Hashtable's key.


/* TestHash.java */

import java.util.*;

public class TestHash
{
public static void main(String[] args)
{
Hashtable<Integer,String> data = new Hashtable<Integer,String>();

//Temp ArrayList is used to store keys of Hashtable
ArrayList<Integer> temp = new ArrayList<Integer>();

data.put(1,"ABC");
data.put(0,"LMN");
data.put(5,"PQR");
data.put(3,"XYZ");

Integer key;

System.out.println("Default Unorderd and Unsorted");
//Iterating Hashtable
Enumeration<Integer> enu = data.keys();
while(enu.hasMoreElements())
{
key=enu.nextElement();
System.out.println(key+" "+data.get(key));

//Putting Hashtable keys in ArrayList
temp.add(key);
}

//Sorting keys of Hashtable
Collections.sort(temp);

//iterating ArrayList using for each loop
System.out.println("Sorted");
for (Integer val : temp)
{
System.out.println(val+" "+data.get(val));
}

//Shuffling keys of Hashtable
Collections.shuffle(temp);

//iterating ArrayList using for each loop
System.out.println("Randomly Iterating");
for (Integer val : temp)
{
System.out.println(val+" "+data.get(val));
}

}
}


/******OUTPUT*******/

Default Unorderd and Unsorted
5 PQR
3 XYZ
1 ABC
0 LMN
Sorted
0 LMN
1 ABC
3 XYZ
5 PQR
Randomly Iterating
3 XYZ
0 LMN
5 PQR
1 ABC

No comments:

Post a Comment