Java - general

Sort Hashtable

A possibility to sort an Hashtable works as follows (Of course, not the Hashtable will be sorted, but the vector with the keys):

package com.sowas.javawiki.examples;
 
import java.util.Hashtable;
 
public class SortedHashtableExample {
 
   public static void main(String[] args) {
      Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
      ht.put("c", 3);
      ht.put("a", 1);
      ht.put("b", 2);
      Vector<String> v = new Vector<String>(ht.keySet());
      Collections.sort(v);
      for (int i=0; i < v. size(); i++) {
         String key = v.elementAt(i);
         System.out.println(key + ": " + ht.get(key));
      }
   }
}




But if you want to sort Key-Value - Values, it is better to use a SortedMap instead of an Hashtable (e.g.: TreeMap):

package com.sowas.javawiki.examples;
 
import java.util.SortedMap;
import java.util.TreeMap;
 
public class SortedMapExample {
 
   public static void main(String[] args) {
      SortedMap<String, Integer> map = new TreeMap<String, Integer>();
      map.put("c", 3);
      map.put("a", 1);
      map.put("b", 2);
 
      for (String key : map.keySet()) {
         System.out.println(key + ": " + map.get(key));
      }
   }
}

Eigene Werkzeuge
Werkzeuge

gratis Counter by GOWEB
seit 9.10.2007