HashMap Sort by Values

 /*  
 Important Methods:   
 class ArrayList;   
           indexOf(Object) = Return last occurances of that object.   
           get(int index) = Returns the element at the specified position in this list.  
 class HashMap:   
      keySet() = returns All the keys present in the HashMap.   
      values() = returns all the values present in the HashMap.   
 */  
 import java.util.*;   
 class HashSortbyValue  
 {  
      public static void main(String []args)  
           {  
      HashMap someMap= new LinkedHashMap();// important line   
      someMap.put("key1",1);  
      someMap.put("key2",3);  
      someMap.put("key3",2);  
      System.out.println("Before Sorting = "+someMap);   
      List keys = new ArrayList(someMap.keySet());   
      List values=new ArrayList(someMap.values());   
      someMap.clear();  
      TreeSet sortedMap= new TreeSet(values);  
      Object[]sortedSet = sortedMap.toArray();   
      for(int i=0;i<sortedSet.length;i++)  
           {  
                someMap.put(keys.get(values.indexOf(sortedSet[i])),sortedSet[i]);   
           }  
      System.out.println("After Sorting = "+someMap);   
      }  
 }  

Post a Comment

1 Comments

  1. This article at takes a different approach using a comparator.

    ReplyDelete