How To Sort Hashmap By Values In Java

Sharing is healthy !!

Hi!! Welcome to flower brackets blog. Today we are going to learn how to sort hashmap by values in java.

So to sort a hashmap we have to insert some key and values and create a linkedlist from the map entries.

Hashmap does not maintain order by default. If there is a need we need to sort it explicitly based on requirement.

Now let’s us see code implementation of hashmap

example: How To Sort Hashmap By Values In Java

import java.util.TreeMap;
import java.util.Map;
import java.util.HashMap;

public class HashMapDemo
{
public static void main(String[] args)
{
// hashmap of string and integer elements
HashMap<String, Integer> mp = new HashMap<String, Integer>(); // adding elements to hashmap
mp.put("orange", 4);
mp.put("mango", 3);
mp.put("strawberry", 6);
mp.put("cherry", 2);
mp.put("apple", 1);
mp.put("pineapple", 5);

System.out.println("HashMap example before sorting : "); for(Map.Entry<String, Integer> entry:mp.entrySet())
{
System.out.println("Unsorted : " + entry.getKey() + " " + entry.getValue());
}

System.out.println("\n");

Map<String, Integer> tm = new TreeMap<String, Integer>(mp);

System.out.println("HashMap example after sorting : "); 

for(Map.Entry<String, Integer> entry:tm.entrySet())
{
System.out.println("Sorted by value : " + entry.getValue());
}
}
}

Output:

How To Sort Hashmap By Values In Java


example: How To Sort Hashmap By key In Java

Also Read – Treeset Java Collection Framework

import java.util.TreeMap;
import java.util.Map;
import java.util.HashMap;

public class HashMapDemo
{
public static void main(String[] args)
{
// hashmap of string and integer elements
HashMap<String, Integer> mp = new HashMap<String, Integer>(); // adding elements to hashmap
mp.put("orange", 4);
mp.put("mango", 3);
mp.put("strawberry", 6);
mp.put("cherry", 2);
mp.put("apple", 1);
mp.put("pineapple", 5);

System.out.println("HashMap example before sorting : "); 

for(Map.Entry<String, Integer> entry:mp.entrySet())
{
System.out.println("Unsorted : " + entry.getKey() + " " + entry.getValue());
}

System.out.println("\n");

Map<String, Integer> tm = new TreeMap<String, Integer>(mp); 

System.out.println("HashMap example after sorting : "); 

for(Map.Entry<String, Integer> entry:tm.entrySet())
{
System.out.println("Sorted by value : " + entry.getKey());
}
}
}

Output:

How To Sort Hashmap By Values In Java


using comparator

import java.text.ParseException;
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.Entry;
import java.util.Set;
import java.util.TreeMap;

public class HashMapExample
{
public static void main(String[] args) throws ParseException  
{
HashMap<String, String> fruitNames = new HashMap<String, String>();
fruitNames.put("Four", "Orange");
fruitNames.put("Three", "Mango");
fruitNames.put("Six", "Strawberry");
fruitNames.put("Two", "Cherry");
fruitNames.put("One", "Apple");
fruitNames.put("Seven", "Grape");
fruitNames.put("Five", "Pineapple");

System.out.println("HashMap example before sorting : "); 

Set<Entry<String, String>> setEntries = fruitNames.entrySet();  for(Entry<String, String> entry : setEntries)
{
System.out.println(entry.getKey() + " : " + entry.getValue()); }
System.out.println("\n");

// Sorting HashMap by keys using TreeMap with mappings of HashMap
TreeMap<String, String> sort = new TreeMap<>(fruitNames); Set<Entry<String, String>> map = sort.entrySet(); System.out.println("HashMap sorting by keys in ascending order : ");
for(Entry<String, String> mapping : map)
{
System.out.println(mapping.getKey() + " : " + mapping.getValue());
}
System.out.println("\n");

// Sorting HashMap by values. To do that i'm using comparator // which takes Map.Entry object
Comparator<Entry<String, String>> valueComparator = new Comparator<Entry<String,String>>()
{
@Override
public int compare(Entry<String, String> e1, Entry<String, String> e2)
{
String v1 = e1.getValue();
String v2 = e2.getValue();
return v1.compareTo(v2);
}
};

// Here i'm converting Set to List because sort method needs a list
List<Entry<String, String>> listEntries = new ArrayList<Entry<String, String>>(setEntries);

// Here i'm sorting HashMap by values using comparator  Collections.sort(listEntries, valueComparator);  LinkedHashMap<String, String> sortedValue = new LinkedHashMap<String, String>(listEntries.size());

// Here i'm copying entries from List to Map
for(Entry<String, String> entry : listEntries)
{
sortedValue.put(entry.getKey(), entry.getValue());
}
System.out.println("HashMap sorting entries by values : "); Set<Entry<String, String>> entrySetSortedByValue = sortedValue.entrySet();
for(Entry<String, String> mapping : entrySetSortedByValue)
{
System.out.println(mapping.getKey() + " : " + mapping.getValue());
}
}
}

Output:

How To Sort Hashmap By Values In Java


Conclusion

That’s it guys. So this is all about how to sort hashmap by values in java. I hope you have understood how to sort hashmap by value and key in java.

You can subscribe to my blog flower brackets if you haven’t already.

If you like this post, do share it across social networks.

Sharing is healthy !!