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.

Comments to: The simplest way to sort HapMap in JAVA

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.


Welcome to Typer

Brief and amiable onboarding is the first thing a new user sees in the theme.
Join Typer