Java Collection How to - Sorting by values in HashMap class using Java








Question

We would like to know how to sorting by values in HashMap class using Java.

Answer

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
//  w  w  w  .  j a  va  2  s.c  o  m
public class Main {
  public static void main(String[] args) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("d", 5);
    map.put("c", 4);
    map.put("b", 2);
    map.put("a", 1);
    
    Integer value[] = new Integer[map.size()];
    
    Set keySet = map.keySet();
    Iterator t = keySet.iterator();
    int a = 0;
    while (t.hasNext()) {
      value[a] = map.get(t.next());
      a++;
    }
    
    Arrays.sort(value);
    
    for (int i = 0; i < map.size(); i++) {
      t = keySet.iterator();
      while (t.hasNext()) {
        String temp = (String) t.next();
        if (value[i].equals(map.get(temp))) {
          System.out.println(value[i] + " = " + temp);
        }
      }
    }
  }
}

The code above generates the following result.