Friday 14 April 2017

Sort HashMap in Java based on Values

Using AraryList with Comparator:
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.Set;
import java.util.Map.Entry;

public class SortByKeyListComp {
     private static void printSortedMap(Map<String, Integer> map) {
           /* Create the entry set. */
           Set<Entry<String, Integer>> set = map.entrySet();
          
           /* Create a list from EntrySet. */
           List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
          
           /* Sort List using the comparator. */
           Collections.sort( list, new Comparator<Map.Entry<String, Integer>>() {
                public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                     return (o2.getValue()).compareTo(o1.getValue() );
                }
           });
          
           /* Print data. */
           for(Map.Entry<String, Integer> entry: list) {
                System.out.println("key#"+entry.getKey()+" value#"+entry.getValue());
           }
     }
    
     /**
      * Driver Method.
      */
     public static void main(String[] args) {
           Map<String, Integer> map = new HashMap<String, Integer>();
           map.put("geeks", 3);
           map.put("nerd", 2);
           map.put("test", 7);
          
           printSortedMap(map);
     }
}


Using TreeMap with Comparator:
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;


class ValueComparator implements Comparator {
     Map map;

     /* Set Map in Constructor. */
     public ValueComparator(Map map) {
           this.map = map;
     }

     /**
      * Compare the values using the default value of the Map.
      */
     public int compare(Object keyA, Object keyB) {
           Comparable valueA = (Comparable) map.get(keyA);
           Comparable valueB = (Comparable) map.get(keyB);
           return valueB.compareTo(valueA);
     }
}

public class SortByKeyTreeComp {

     public static Map sortByValue(Map unsortedMap) {
           /* Pass Map to ValueComparator so we can compare on the basic from defualt key.*/
           ValueComparator vc = new ValueComparator(unsortedMap);
           Map sortedMap = new TreeMap(vc);
           sortedMap.putAll(unsortedMap);
           return sortedMap;
     }

     public static void main(String[] args) {
           HashMap<String, Integer> map = new HashMap<String, Integer>();
           map.put("geeks", 3);
           map.put("nerd", 2);
           map.put("test", 7);

           System.out.println(map);
           Map sortedMap = sortByValue(map);
           System.out.println(sortedMap);
     }

}

2 comments:

Related Posts Plugin for WordPress, Blogger...