java

How to Sort a HashMap by Key and by Value in Java

We already know that HashMap does not maintain any order by default. So to sort a HashMap, we have to sort it explicitly according to the requirement. In this tutorial, we are going to see how to sort a HashMap by keys using TreeMap and by values using Comparator.
 

Sort a HashMap by key

In this example, we’ll sort a HashMap based on keys using the TreeMap class.

import java.util.*;

public class SortHashmap {

    public static void main(String[] args) {

         HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
         hashmap.put(7, "B");
         hashmap.put(15, "D");
         hashmap.put(2, "X");
         hashmap.put(98, "U");

         Map<Integer, String> map = new TreeMap<Integer, String>(hashmap); 
         Set set = map.entrySet();
         Iterator it = set.iterator();
         while(it.hasNext()) {
              Map.Entry entry = (Map.Entry)it.next();
              System.out.println(entry.getKey() + ": "+entry.getValue());
         }
    }
}

Output:

2: X
7: B
15: D
98: U

 
[st_adsense]  

Sort a HashMap by value

In this example, we’ll sort a HashMap based on keys using the Comparator interface.

import java.util.*;

public class SortHashmap {
  public static void main(String[] args) {

      HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
      hashmap.put(7, "B");
      hashmap.put(15, "D");
      hashmap.put(2, "X");
      hashmap.put(98, "U");

      Map<Integer, String> map = sort(hashmap); 
      Set set2 = map.entrySet();
      Iterator it = set2.iterator();
      while(it.hasNext()) {
           Map.Entry entry = (Map.Entry)it.next();
           System.out.println(entry.getKey() + ": "+entry.getValue());
      }
  }

  private static HashMap sort(HashMap map) {
       List linkedlist = new LinkedList(map.entrySet());

       Collections.sort(linkedlist, new Comparator() {
            public int compare(Object o1, Object o2) {
               return ((Comparable) ((Map.Entry) (o1)).getValue())
                  .compareTo(((Map.Entry) (o2)).getValue());
            }
       });

       HashMap sortedHashMap = new LinkedHashMap();
       for (Iterator it = linkedlist.iterator(); it.hasNext();) {
              Map.Entry entry = (Map.Entry) it.next();
              sortedHashMap.put(entry.getKey(), entry.getValue());
       } 
       return sortedHashMap;
  }
}

Output:

2: X
7: B
15: D
98: U
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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