The simplest way to sort HapMap

The simplest way to sort HashMap in JAVA

The way JAVA data-structures is it is not always easy to sort HashMaps. So here is a piece of code I frequently use to sort HashMap of type String, Long in JAVA

// function to sort hashmap by values  public static HashMap<String, Long> sortByValue(HashMap<String, Long> hm) {
    // Create a list from elements of HashMap
    List<Map.Entry<String, Long>> list =
        new LinkedList<>(hm.entrySet());
    // Sort the list
    Collections.sort(list, new Comparator<Map.Entry<String, Long>>() {
      public int compare(Map.Entry<String, Long> o1,
          Map.Entry<String, Long> o2) {
        return (o1.getValue()).compareTo(o2.getValue());
      }
    });
    // put data from sorted list to hashmap
    HashMap<String, Long> temp = new LinkedHashMap<>();
    for (Map.Entry<String, Long> aa : list) {
      temp.put(aa.getKey(), aa.getValue());
    }
    return temp;
}

You can change “Long” to any other datatype like Integer, Float, etc.

No Comments

Post A Comment