Java Collection How to - Sort HashMap with duplicate values








Question

We would like to know how to sort HashMap with duplicate values.

Answer

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
//from ww  w  .ja  v  a 2s  . com
public class Main {

  public static Map<String, Integer> sortByValue(Map<String, Integer> map) {
    List list = new LinkedList(map.entrySet());
    Collections.sort(list, new Comparator() {

      @Override
      public int compare(Object o1, Object o2) {
        return ((Comparable) ((Map.Entry) (o2)).getValue())
            .compareTo(((Map.Entry) (o1)).getValue());
      }
    });

    Map result = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext();) {
      Map.Entry entry = (Map.Entry) it.next();
      result.put(entry.getKey(), entry.getValue());
    }
    return result;
  }

  public static void main(String[] args) {

    HashMap<String, Integer> map = new HashMap<String, Integer>();

    map.put("item1", 1);
    map.put("item2", 2);
    map.put("item3", 1);
    map.put("item4", 7);
    map.put("item5", 3);
    map.put("item6", 4);

    for (Map.Entry<String, Integer> entry : map.entrySet()) {
      System.out.println("Item is:" + entry.getKey() + " with value:"
          + entry.getValue());
    }

    Map<String, Integer> sortedMap = sortByValue(map);

    for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
      System.out.println("Item is:" + entry.getKey() + " with value:"
          + entry.getValue());
    }
  }
}

The code above generates the following result.