- How to Sort HashMap in Java based on Keys and Values
- Steps to sort HashMap by values
- Steps to sort HashMap by keys
- HashMap Sorting by Keys and Values in Java Example
- How to Sort a HashMap by Value in Java?
- Sorting HashMap by Value Simple Example
- Another Example of Sorting HashMap by Value
- Sorting the HashMap using a custom comparator
- Conclusion
How to Sort HashMap in Java based on Keys and Values
HashMap is not meant to keep entries in sorted order, but if you have to sort HashMap based upon keys or values, you can do that in Java. Sorting HashMap on keys is quite easy, all you need to do is to create a TreeMap by copying entries from HashMap. TreeMap is an implementation of SortedMap and keeps keys in their natural order or a custom order specified by Comparator provided while creating TreeMap. This means you can process entries of HashMap in sorted order but you cannot pass a HashMap containing mappings in a specific order, this is just not possible because HashMap doesn’t guarantee any order.
On other hand, sorting HashMap by values is rather complex because there is no direct method to support that operation. You need to write code for that. In order to sort HashMap by values you can first create a Comparator, which can compare two entries based on values.
Then get the Set of entries from Map, convert Set to List, and use Collections.sort(List) method to sort your list of entries by values by passing your customized value comparator. This is similar to how you sort an ArrayList in Java.
Half of the job is done by now. Now create a new LinkedHashMap and add sorted entries into that. Since LinkedHashMap guarantees insertion order of mappings, you will finally have a Map where contents are sorted by values.
Steps to sort HashMap by values
- Get all entries by calling entrySet() method of Map
- Create a custom Comparator to sort entries based upon values
- Convert entry set to list
- Sort entry list by using Collections.sort() method by passing your value comparator
- Create a LinkedHashMap by adding entries in sorted order.
Steps to sort HashMap by keys
There are two ways to sort HashMap by keys, first by using TreeMap and second by using LinkedHashMap . If you want to sort using TreeMap then it’s simple, just create a TreeMap by copying the content of HashMap.
On the other hand, if you want to create a LinkedHashMap then you first need to get a key set, convert that Set to a List, sort that List, and then add them into LHM in the same order. Remember HashMap can contain one null key but duplicate keys are not allowed.
HashMap Sorting by Keys and Values in Java Example
Here is our sample Java program to sort a HashMap first by keys and then by values. This program is divided into two part, the first part sorts HashMap by keys, and the second part sorts it by values. The second part is more tricky the first part as there is no native Map implementation that supports any order for values.
In order to sort a HashMap by values, we had to create our own Comparator implementation which compares each entry by values to arrange them in a particular order. You can see that our valueComparator overrides compare() method and accepts two entries. Later it retrieves values from those entries and compare them and return result.
Since there is no method in Java Collection API to sort Map, we need to use Collections.sort() method which accepts a List. This involves creating a temporary ArrayList with entries for sorting purpose and then again copying entries from sorted ArrayList to a new LinkedHashMap to keep them in sorted order.
Finally, we create a HashMap from that LinkedHashMap , which is what we needed.
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; /** * How to sort HashMap in Java by keys and values. * HashMap doesn't guarantee any order, so you cannot rely on it, even if * it appear that it storing entries in a particular order, because * it may not be available in future version e.g. earlier HashMap stores * integer keys on the order they are inserted but from Java 8 it has changed. * * @author WINDOWS 8 */ public class HashMapSorting< public static void main(String args[]) throws ParseException < // let's create a map with Java releases and their code names HashMap codenames = new HashMap(); codenames.put("JDK 1.1.4", "Sparkler"); codenames.put("J2SE 1.2", "Playground"); codenames.put("J2SE 1.3", "Kestrel"); codenames.put("J2SE 1.4", "Merlin"); codenames.put("J2SE 5.0", "Tiger"); codenames.put("Java SE 6", "Mustang"); codenames.put("Java SE 7", "Dolphin"); System.out.println("HashMap before sorting, random order "); Setentries = codenames.entrySet(); for(Entry entry : entries)< System.out.println(entry.getKey() + " ==> " + entry.getValue()); > // Now let's sort HashMap by keys first // all you need to do is create a TreeMap with mappings of HashMap // TreeMap keeps all entries in sorted order TreeMap sorted = new TreeMap<>(codenames); Set mappings = sorted.entrySet(); System.out.println("HashMap after sorting by keys in ascending order "); for(Entry mapping : mappings)< System.out.println(mapping.getKey() + " ==> " + mapping.getValue()); > // Now let's sort the HashMap by values // there is no direct way to sort HashMap by values but you // can do this by writing your own comparator, which takes // Map.Entry object and arrange them in order increasing // or decreasing by values. Comparator valueComparator = new Comparator>() < @Override public int compare(Entry e1, Entry e2) < String v1 = e1.getValue(); String v2 = e2.getValue(); return v1.compareTo(v2); > >; // Sort method needs a List, so let's first convert Set to List in Java List listOfEntries = new ArrayList (entries); // sorting HashMap by values using comparator Collections.sort(listOfEntries, valueComparator); LinkedHashMap sortedByValue = new LinkedHashMap(listOfEntries.size()); // copying entries from List to Map for(Entry entry : listOfEntries)< sortedByValue.put(entry.getKey(), entry.getValue()); > System.out.println("HashMap after sorting entries by values "); Set entrySetSortedByValue = sortedByValue.entrySet(); for(Entry mapping : entrySetSortedByValue)< System.out.println(mapping.getKey() + " ==> " + mapping.getValue()); > > > Output: HashMap before sorting, random order Java SE 7 ==> Dolphin J2SE 1.2 ==> Playground Java SE 6 ==> Mustang J2SE 5.0 ==> Tiger J2SE 1.3 ==> Kestrel J2SE 1.4 ==> Merlin JDK 1.1.4 ==> Sparkler HashMap after sorting by keys in ascending order J2SE 1.2 ==> Playground J2SE 1.3 ==> Kestrel J2SE 1.4 ==> Merlin J2SE 5.0 ==> Tiger JDK 1.1.4 ==> Sparkler Java SE 6 ==> Mustang Java SE 7 ==> Dolphin HashMap after sorting entries by values Java SE 7 ==> Dolphin J2SE 1.3 ==> Kestrel J2SE 1.4 ==> Merlin Java SE 6 ==> Mustang J2SE 1.2 ==> Playground JDK 1.1.4 ==> Sparkler J2SE 5.0 ==> Tiger
That’s all about how to sort HashMap by keys and values in Java. Remember, HashMap is not intended to keep entries in sorted order, so if you have a requirement to always keep entries in a particular order, don’t use HashMap instead use TreeMap or LinkedHashMap .
This method should only be used to cater to Adhoc needs where you receive a HashMap from some part of legacy code and you have to sort it first to process entries. If you have control of creating the Map initially prefer the right implementation of Map than just HashMap.
How to Sort a HashMap by Value in Java?
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
HashMap in java provides quick lookups. They store items in “key, value” pairs. To get a value from the HashMap, we use the key corresponding to that entry. HashMaps are a good method for implementing Dictionaries and directories. Key and Value can be of different types (eg — String, Integer). We can sort the entries in a HashMap according to keys as well as values. In this tutorial we will sort the HashMap according to value. The basic strategy is to get the values from the HashMap in a list and sort the list. Here if the data type of Value is String, then we sort the list using a comparator. To learn more about comparator, read this tutorial. Once we have the list of values in a sorted manner, we build the HashMap again based on this new list. Let’s look at the code.
Sorting HashMap by Value Simple Example
We first get the String values in a list. Then we sort the list. To sort the String values in the list we use a comparator. This comparator sorts the list of values alphabetically.
Collections.sort(list, new ComparatorString>() public int compare(String str, String str1) return (str).compareTo(str1); > >);
Once, we have sorted the list, we build the HashMap based on this sorted list. The complete code is as follows :
package com.journaldev.collections; 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; public class Main public static void main(String[] args) HashMapString, String> map = new HashMap>(); LinkedHashMapString, String> sortedMap = new LinkedHashMap>(); ArrayListString> list = new ArrayList>(); map.put("2", "B"); map.put("8", "A"); map.put("4", "D"); map.put("7", "F"); map.put("6", "W"); map.put("19", "J"); map.put("1", "Z"); for (Map.EntryString, String> entry : map.entrySet()) list.add(entry.getValue()); > Collections.sort(list, new ComparatorString>() public int compare(String str, String str1) return (str).compareTo(str1); > >); for (String str : list) for (EntryString, String> entry : map.entrySet()) if (entry.getValue().equals(str)) sortedMap.put(entry.getKey(), str); > > > System.out.println(sortedMap); > >
HashMap entries are sorted according to String value.
Another Example of Sorting HashMap by Value
package com.JournalDev; 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; public class Main public static void main(String[] args) HashMapString, Integer> map = new HashMap>(); LinkedHashMapString, Integer> sortedMap = new LinkedHashMap>(); ArrayListInteger> list = new ArrayList>(); map.put("A", 5); map.put("B", 7); map.put("C", 3); map.put("D", 1); map.put("E", 2); map.put("F", 8); map.put("G", 4); for (Map.EntryString, Integer> entry : map.entrySet()) list.add(entry.getValue()); > Collections.sort(list); for (int num : list) for (EntryString, Integer> entry : map.entrySet()) if (entry.getValue().equals(num)) sortedMap.put(entry.getKey(), num); > > > System.out.println(sortedMap); > >
Here HashMap values are sorted according to Integer values.
Sorting the HashMap using a custom comparator
If you notice the above examples, the Value objects implement the Comparator interface. Let’s look at an example where our value is a custom object. We can also create a custom comparator to sort the hash map according to values. This is useful when your value is a custom object. Let’s take an example where value is a class called ‘Name’. This class has two parameters, firstName and lastName. The code for class Name is :
package com.JournalDev; public class Name String firstName; String lastName; Name(String a, String b) firstName=a; lastName=b; > public String getFirstName() return firstName; > >
ComparatorName> byName = (Name obj1, Name obj2) -> obj1.getFirstName().compareTo(obj2.getFirstName());
We are sorting the names according to firstName, we can also use lastName to sort. Rather than using a list to get values from the map, we’ll be using LinkedHashMap to create the sorted hashmap directly. The complete code is :
public static void main(String[] args) HashMapInteger, Name> hmap = new HashMapInteger, Name>(); Name name1 = new Name("Jayant", "Verma"); Name name2 = new Name("Ajay", "Gupta"); Name name3 = new Name("Mohan", "Sharma"); Name name4 = new Name("Rahul", "Dev"); hmap.put(9, name1); hmap.put(1, name2); hmap.put(6, name3); hmap.put(55, name4); ComparatorName> byName = (Name obj1, Name obj2) -> obj1.getFirstName().compareTo(obj2.getFirstName()); LinkedHashMapInteger, Name> sortedMap = hmap.entrySet().stream() .sorted(Map.Entry.Integer, Name>comparingByValue(byName)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); //printing the sorted hashmap Set set = sortedMap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) Map.Entry me2 = (Map.Entry) iterator.next(); System.out.print(me2.getKey() + ": "); System.out.println(hmap.get(me2.getKey()).firstName + " "+hmap.get(me2.getKey()).lastName ); > >
1: Ajay Gupta 9: Jayant Verma 6: Mohan Sharma 55: Rahul Dev
Conclusion
This tutorial covered sorting of HashMap according to Value. Sorting for String values differs from Integer values. String values require a comparator for sorting. Whereas, Integer values are directly sorted using Collection.sort().
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us