javacodex.com
Java Examples
Java Examples
memu home questions

Sorting A HashMap Using A TreeMap

This java example shows you how to sort a HashMap using a TreeMap.

Source: (HashMapSort.java)

import java.util.*;
 
public class HashMapSort {
 
   public static void main(String args[]){
 
      HashMap<String, String> map = new HashMap<String, String>();
      map.put("5", "E");
      map.put("2", "B");
      map.put("1", "A");
      map.put("4", "D");
      map.put("3", "C");
      System.out.println("Unsorted:");
      printMap(map);
 
      System.out.println("Sorted:");
      Map<String, String> treeMap = new TreeMap<String, String>(map);
      printMap(treeMap);
   } 
 
   public static void printMap(Map<String, String> map) {
      Iterator<String> it = map.keySet().iterator();
      while(it.hasNext()){
         String key = it.next();
         System.out.println(key + " : " + map.get(key));
      }
   }
}
 

Output:

# java HashMapSort 
Unsorted:
3 : C
2 : B
1 : A
5 : E
4 : D
Sorted:
1 : A
2 : B
3 : C
4 : D
5 : E

Contact: javacodex@yahoo.com