Java - How to sort a Map

By xngo on June 26, 2019

In this article, I'm going to show you how to sort a HashMap in Java.

Sort by key using a TreeMap

We are going to exploit the property of the TreeMap. All entries added to the TreeMap are sorted according to the lexicographical order of its keys. The main idea is to copy all data from the HashMap to TreeMap. Therefore, the sorting process is automatically done by the TreeMap. We don't have to do anything else. Here is a code example. It will sort by fruit name.

import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeMap;
 
public class SortMapByKeyUsingTreeMap {
 
    public static void main(String[] args) {
 
        // Create a HashMap with values.
        Map<String, Double> unsortedMap = new HashMap<String, Double>();
        unsortedMap.put("pineapple", 4.99);
        unsortedMap.put("banana", 1.85);
        unsortedMap.put("guava", 0.85);
 
        // Push all the data from our HashMap into the TreeMap.
        Map<String, Double> treeMap = new TreeMap<String, Double>(unsortedMap);
 
        // Display all elements from treeMap.
        Set< Map.Entry<String, Double> > treeSet = treeMap.entrySet();
        for (Map.Entry<String, Double> entry:treeSet) { 
            System.out.println("key: "+entry.getKey()+", Value: "+entry.getValue()); 
        }         
    }
}

Output

key: banana, Value: 1.85
key: guava, Value: 0.85
key: pineapple, Value: 4.99

Sort by key using comparator

It is nice that TreeMap sorts the keys for us but what if I want to sort the keys using my own order. In this case, you have to provide TreeMap with your own comparator that contains your ordering logic. Here is a code example. It will sort on the second charactor of the fruit name in descending order.

import java.util.Map;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeMap;
 
public class SortMapByKeyUsingComparator {
 
    // My comparator with my own order logic:
    //        Sort on 2nd character of the fruit name in descending order.
    public static class SortOn2ndChar implements Comparator<String>
    {
      public int compare(String s1, String s2)
      {
          char s1char = s1.charAt(1); // Get 2nd character of 1st string.
          char s2char = s2.charAt(1); // Get 2nd character of 2nd string.
          if (s1char > s2char)
              return -1;
          else if(s1char < s2char)
              return 1;
          else
              return 0;
      }
    }
 
    public static void main(String[] args) {
 
        // Create a HashMap with values.
        Map<String, Double> unsortedMap = new HashMap<String, Double>();
        unsortedMap.put("pineapple", 4.99);
        unsortedMap.put("banana", 1.85);
        unsortedMap.put("guava", 0.85);
 
        // Add my own comparator & push all the data from our HashMap into the TreeMap.
        Map<String, Double> treeMap = new TreeMap<String, Double>(new SortOn2ndChar());
        treeMap.putAll(unsortedMap);
 
        // Display all elements from treeMap.
        Set< Map.Entry<String, Double> > treeSet = treeMap.entrySet();
        for (Map.Entry<String, Double> entry:treeSet) { 
            System.out.println("key: "+entry.getKey()+", Value: "+entry.getValue()); 
        }         
    }
}

Output

key: guava, Value: 0.85         // 2nd char = u
key: pineapple, Value: 4.99     // 2nd char = i
key: banana, Value: 1.85        // 2nd char = a

Github

  • https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/lang/SortMapByKeyUsingTreeMap.java
  • https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/lang/SortMapByKeyUsingComparator.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.