Sorting a HashMap according to values in Java


As we know that Hash map in Java does not maintain insertion order either by key or by order.Also it does not maintain any other order while adding entries to it.

Now in order to sort a hash map according to the values mapped to its corresponding keys we first need to get all values of map considering that hash map has unique values only.Now put all the values in a list and sort this list with the comparator or comparable interface of Java.

As we get sorted list of unique values now get corresponding keys from the map and put the value key pair in new tree map so that again the insertion order is maintained according to the values.After insertion we would transverse same tree map which is sorted and is our resultant sorted map.

Example

Live Demo

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class HashMapSortByValue {
   public static void main(String[] args) {
      HashMap<String, String> hMap = new HashMap<>();
      LinkedHashMap<String, String> sortedMap = new LinkedHashMap<>();
      ArrayList<String> list = new ArrayList<>();
      hMap.put("5", "Akshay");
      hMap.put("8", "Veer");
      hMap.put("3", "Guang");
      hMap.put("7", "Bakshi");
      hMap.put("2", "TomTom");
      hMap.put("10", "Chang");
      hMap.put("1", "Sandy");
      for (Map.Entry<String, String> entry : hMap.entrySet()) {
         list.add(entry.getValue());
      }
      Collections.sort(list, new Comparator<String>() {
         public int compare(String str, String str1) {
            return (str).compareTo(str1);
         }
      });
      for (String str : list) {
         for (Entry<String, String> entry : hMap.entrySet()) {
            if (entry.getValue().equals(str)) {
               sortedMap.put(entry.getKey(), str);
            }
         }
      }
      System.out.println(sortedMap);
   }
}

Output

{5 = Akshay, 7 = Bakshi, 10 = Chang, 3 = Guang, 1 = Sandy, 2 = TomTom, 8 = Veer}

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jul-2019

451 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements