Java Data Structure How to - Sort a map on key and value








Question

We would like to know how to sort a map on key and value.

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;
/* w  w w .jav  a 2  s  .  c om*/
public class Main {
  public static void main(String[] args) {
    Map<String, String> unsortMap = new HashMap<String, String>();
    unsortMap.put("1", "1");
    unsortMap.put("2", "A");
    unsortMap.put("3", "2");
    Iterator iterator = unsortMap.entrySet().iterator();
    for (Map.Entry entry : unsortMap.entrySet()) {
      System.out.println("Key : " + entry.getKey() + " Value : "
          + entry.getValue());
    }
    Map<String, String> sortedMap = sortByComparator(unsortMap);
    for (Map.Entry entry : sortedMap.entrySet()) {
      System.out.println("Key : " + entry.getKey() + " Value : "
          + entry.getValue());
    }
  }
  private static Map sortByComparator(Map unsortMap) {
    List list = new LinkedList(unsortMap.entrySet());
    Collections.sort(list, new Comparator() {
      public int compare(Object o1, Object o2) {
        return ((Comparable) ((Map.Entry) (o1)).getValue())
            .compareTo(((Map.Entry) (o2)).getValue());
      }
    });
    Map sortedMap = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext();) {
      Map.Entry entry = (Map.Entry) it.next();
      sortedMap.put(entry.getKey(), entry.getValue());
    }
    return sortedMap;
  }
}

The code above generates the following result.