Home > Tutorial > Java HashMap Sort By Value

Java HashMap Sort By Value

We already went through a tutorial on how to sort a Java HashMap using the keys, which is pretty simple using the Java TreeMap class. That tutorial is found in the Java Reference section below.

Sorting a Java HashMap by Value is slightly more complicated that involves a the use of some additional Java classes and Interface.

We will use the Comparator Interface to do our sorting. If your not familiar with it, the Comparator Interface is used to order the objects of user-defined classes. Our sample code below includes a custom comparator to do the sorting.


Java HashMap Sort By Value

The sort by value portion is all done in our sortHashMapByValue() method. There is a good amount of logic going on in this method. Start by converting our HashMap to a list of Map objects. Next task is to create a custom comparator method and feed that into the Collections.sort() method. Finally we populate a new Map object with our sorted key/value pairs by value.

package com.jcd.java.tutorials;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


public class JavaSortHashMapByValue 
{

	public static void main(String[] args) 
	{

		//Create an empty HashMap to hold String as Key and Integer as Value
		HashMap<String,Integer> javaCodeDepotHashMap = new HashMap<String,Integer>();
		
		//Add some kay/value pairs
		javaCodeDepotHashMap.put("Seymour", 25);
		javaCodeDepotHashMap.put("Smedley", 35);
		javaCodeDepotHashMap.put("Vince", 21);
		javaCodeDepotHashMap.put("Kevin", 45);
		javaCodeDepotHashMap.put("Arthur", 95);
		javaCodeDepotHashMap.put("Arthur", 94);
		
		System.out.println("Unsorted HashMap:\n");
		
		//Loop through our HashMap and print out key/value pairs
		for (Map.Entry<String,Integer> myEntry : javaCodeDepotHashMap.entrySet()) 
		{
			System.out.println("Key="+myEntry.getKey()+" Value="+myEntry.getValue());
		}
		
		//Call our custom sortHashMapByValue() method and give it our unsorted hashmap
		Map<String, Integer> javaCodeDepotHashMapSorted = sortHashMapByValue(javaCodeDepotHashMap);
		
		System.out.println("\nSorted HashMap By Value:\n");
		
		//Loop through our HashMap and print out key/value pairs
		for (Map.Entry<String,Integer> myEntry : javaCodeDepotHashMapSorted.entrySet()) 
		{
			System.out.println("Key="+myEntry.getKey()+" Value="+myEntry.getValue());
		}
		
	}
	
	//Method to sort HashMap by value
	public static Map<String, Integer> sortHashMapByValue(Map<String,Integer> notSortedMap)
	{
		
		//Start by converting out HashMap to a list of Map objects
		List<Map.Entry<String,Integer>> myList = new LinkedList<Map.Entry<String,Integer>>(notSortedMap.entrySet());
		
		//Use Collections to sort our List 
		Collections.sort(myList, new Comparator<Map.Entry<String,Integer>>() 
		{
			//Define our compare method
            public int compare(Map.Entry<String,Integer> objectA, Map.Entry<String,Integer> objectB) 
            {
                return (objectA.getValue()).compareTo(objectB.getValue());
            }
        });
		
		//Create a new map object to hold our sorted list
		Map<String,Integer> newlySortedMap = new LinkedHashMap<String,Integer>();
		
		//Add sorted key/values sorted by valeue into our new map
        for (Map.Entry<String,Integer> mapEntry : myList) 
        {
        	newlySortedMap.put(mapEntry.getKey(), mapEntry.getValue());
        }
        
        return newlySortedMap;

	}

}


Java HashMap Sort By Value Output

Unsorted HashMap:

Key=Vince Value=21
Key=Kevin Value=45
Key=Smedley Value=35
Key=Arthur Value=94
Key=Seymour Value=25

Sorted HashMap By Value:

Key=Vince Value=21
Key=Seymour Value=25
Key=Smedley Value=35
Key=Kevin Value=45
Key=Arthur Value=94



Concluding Comments

Hope you enjoyed our tutorial on how to sort a Java HashMap by value. If you have a quick method to sort a HashMap by value, please post and share it.



Java References:

Smedley
Posted by

Smedley

Smedley has been doing software development for years, which mainly docues on C and C++. In the past number of years, he has focused on Java programming.

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot