How to sort HashMap by value?

In this article, we will learn how to sort HashMap by value. As we know HashMap does not guarantee to the ordering of elements, this is a bit tricky to sort HashMap by value

Let us understand the steps to sort HashMap by value.

  1. Use entryset() method to get all entries available in HashMap.
  2. As we want to sort the values, we need a comparator to sort the values of HashMap
  3. Now convert the Entry to List
  4. Now we can sort the List of Entry using Collections.sort() method.
  5. Create a LinkedHashMap by adding entries in sorted order.

Code Snippet

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

class ValueComparator implements Comparator<Entry<String, Integer>> {

	@Override
	public int compare(Entry<String, Integer> entry1, Entry<String, Integer> entry2) {
		Integer value1 = entry1.getValue(); 
		Integer value2 = entry2.getValue(); 
		return value1.compareTo(value2);
	}

}


public class SortHashMapByValue {

	public static void main(String[] args) {
		
		HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
		
		// Initialize hashMap
		initializeHashMap(hashMap);
		
		System.out.println("-------------Before Sorting----------");
		
		//iteration on original hashMap
		iterateMap(hashMap);
		
		//create set of entry
		Set<Entry<String, Integer>> setOfEntries = hashMap.entrySet();
		
		//create list from set of entry
		List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(setOfEntries);
		
		//create comparator
		Comparator<Entry<String, Integer>> comp = new ValueComparator();
		
		
		//inbuilt method tom sort list using comparator
		Collections.sort(list, comp);
		
		//create LinkedHashMap instance
		LinkedHashMap<String, Integer> sortedByValue = new LinkedHashMap<String, Integer>(list.size()); 
		

		for(Entry<String, Integer> entry : list){
			sortedByValue.put(entry.getKey(), entry.getValue()); 
		}
		
		System.out.println("-------------After Sorting----------");
		
		
		//iteration on sorted by value --> linkedHashMap
		iterateMap(sortedByValue);
				
	}


	/**
	 * @param hashMap
	 */
	private static void initializeHashMap(HashMap<String, Integer> hashMap) {
		hashMap.put("Java", 1);
		hashMap.put(".Net", 4);
		hashMap.put("HTML", 3);
		hashMap.put("Hadoop", 2);
		hashMap.put("Spark", 7);
		hashMap.put("HBase", 6);
		hashMap.put("C#", 9);
	}

	/**
	 * @param hashMap
	 */
	private static void iterateMap(Map<String, Integer> hashMap) {
		for(Entry<String, Integer> hashEntry : hashMap.entrySet()){
			System.out.println("Key = " +hashEntry.getKey()+ " , "+ "Value = "+hashEntry.getValue());
		}
	}
}

Output

-------------Before Sorting----------
Key = C# , Value = 9
Key = Java , Value = 1
Key = Hadoop , Value = 2
Key = .Net , Value = 4
Key = HTML , Value = 3
Key = Spark , Value = 7
Key = HBase , Value = 6
-------------After Sorting----------
Key = Java , Value = 1
Key = Hadoop , Value = 2
Key = HTML , Value = 3
Key = .Net , Value = 4
Key = HBase , Value = 6
Key = Spark , Value = 7
Key = C# , Value = 9

In this article, we learnt how to sort HashMap by value.

Article tagged as
Author
Author: Amit Gupta
Published On: 24/04/2017
Last revised On: 29/09/2018
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media