Saturday 28 May 2016

Write program to sort map by value


Sample Program:-


import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.Comparator;  
 import java.util.HashMap;  
 import java.util.List;  
 import java.util.Map;  
 import java.util.Map.Entry;  
 import java.util.Set;  
 /**  
  * @author Dixit  
  *  
  */  
 public class SortMapByValues {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           // Suppose map contains roll number as key and Name as values  
           Map<Integer, String> studentMap = new HashMap<Integer, String>();  
           studentMap.put(1, "Satish");  
           studentMap.put(2, "Ashish");  
           studentMap.put(3, "Manish");  
           studentMap.put(4, "Rajnish");  
           studentMap.put(5, "Kavita");  
           Set<Map.Entry<Integer, String>> set = studentMap.entrySet();  
           List<Map.Entry<Integer, String>> list = new ArrayList<Map.Entry<Integer, String>>(  
                     set);  
           Collections.sort(list, new Comparator<Map.Entry<Integer, String>>() {  
                @Override  
                public int compare(Entry<Integer, String> o1,  
                          Entry<Integer, String> o2) {  
                     return o1.getValue().compareTo(o2.getValue());  
                }  
           });  
           for (Map.Entry<Integer, String> entry : list) {  
                System.out.println(entry.getKey() + " " + entry.getValue());  
           }  
      }  
 }  


Output:  
 2 Ashish  
 5 Kavita  
 3 Manish  
 4 Rajnish  
 1 Satish  


Explanation:-
In above program, I have created HashMap which contains key as roll number and values as name. First I get the entryset from the map and store it into Set. Then I convert the Set into the list so that I can sort it using custom comparator .I have used Collections utility class sort method for sorting and I have provided custom comparator to it.

Enjoy Programming :)

No comments:

Post a Comment