Sorting Hashtable in Asc/Desc Order

Discussions

Web tier: servlets, JSP, Web frameworks: Sorting Hashtable in Asc/Desc Order

  1. Sorting Hashtable in Asc/Desc Order (3 messages)

    Hi,
     Can anyone let me know how to sort Hashtable Ascending order. I have values set in Hashtable which are displayed in JSP page with <logic:iterator> struts.
     Does anyone know how to display keys/values of hashtable in Ascending Order..

    thanks,
    sachin

    Threaded Messages (3)

  2. USE TREE MAPs ...............like this:
                
    assume "yourHashTable" is the instance of a Hastable that contains all values:


    Iterator itr;
    TreeMap treeMap = new TreeMap(yourHashTable);
    itr = treeMap.keySet().iterator();
       while (itr.hasNext()) {
             String key = (String)itr.next();
             String value = treeMap.get(clusterKey).toString();
             System.out.println("key is ="+key);
             System.out.println("value is="+value);
       }


    GOOD LUCK !!!
  3. java.util.TreeMap[ Go to top ]

    use java.util.TreeMap instead of java.util.Hashtable
  4. Sorting Hashtable Asc/Desc order[ Go to top ]

    Hiii,

    Other way to sort Hashtable:

    Code:
    public class HashSort
    {

    public static void main(String args[])
    {
    //Creates Hashtable object
    Hashtable myHashTable = new Hashtable();
                    
                    //Put values in hashtable
    myHashTable.put("A","String:A");
    myHashTable.put("E","String:E");
    myHashTable.put("Q","String:Q");
    myHashTable.put("Z","String:Z");
    myHashTable.put("B","String:B");
                    
                    //Creates vector object
    Vector vecKeys = new Vector();

                    //Gets keys from hashtable
    Enumeration enum = myHashTable.keys();

    while (enum.hasMoreElements())
    {
    vecKeys.add(enum.nextElement());
      }
                    
                    //Sorts vector in Ascending order
    Collections.sort(vecKeys);
                    
                    //Displays values using Key
    for(int i=0;i<vecKeys.size();i++)
    {
    String key = (String)vecKeys.get(i);
    String value = myHashTable.get(key).toString();
    System.out.println("key is ="+key);
    System.out.println("value is="+value);
    }

    }//end of main
    }


    Cheers,
    -Raghav