How to Sort HashMap by Key and Value
HashMap is a class in Java that implements Map interface and holds values based on an unique key.As we know HashMap is an unsorted and unordered Map. Hence, requirements come where we need to sort the HashMap either by its key or values.In this post, we will take a look into how to sort a HashMap by key as well as by value.
Sort HashMap by Key
As we know there is an implementation of NavigableMap interface, known as TreeMap which also holds a key value pair but maintains the key sorted(natural order) in ascending order by default.Hence, to sort a HashMap by it's key it is only required to convert existing HashMap into a TreeMap.Apart from this, we can also define our custom sort order by implementing Comparable or Comparator Interface to sort a TreeMap.
First, let us take a look into how to sort a HashMap by it's key in natural order.
Map<String, String> unsortedMap = new HashMap<Integer,String>(); //Convert HashMap to TreeMap.It will be sorted in natural order. Map<String,String> treeMap = new TreeMap<String,String>(unsortedMap);
Above code snippet will sort the Map by key in ascending order and it is a natural sorting.Now to sort it in descending order or to sort the map with custom object keys, we need to implement Comparator as below:
Map<Integer,String> unsortedMap = new Hashmap<Integer,String>(); Map<Integer,String> treeMap = new TreeMap<Integer,String>( new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1);//sort in descending order } });
Other Interesting Posts Hello World Java Program Breakup Serialization and Deserialization in Java with Example Convert HashMap to List in Java Why wait(),notify(),notifyAll() defined in object class in Java How to use Comparable and Comparator in Java with Example
Sort HashMap by Values
Sorting a Hashmap by values is little tricky as TreeMap is unable to sort the Map by it's values.To sort a HashMap by it's values, we need to convert the existing Map into a List and then sort this list by using Comparator interface and then again put this sorted list back to a Map.
Map<String, Integer> unsortedMap = new HashMap<String, Integer>(); //convert map to a List List<Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(unsortedMap.entrySet()); //sorting the list with a comparator Collections.sort(list, new Comparator<Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); //convert sortedMap back to Map Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); for (Entry<String, Integer> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); } }
Conclusion
I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.
If You Appreciate This, You Can Consider:
- We are thankful for your never ending support.
About The Author
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.
Further Reading on Core Java
2. Why Wait Notify Notifyall Defined In Object Class
3. Random Password Generator Java
4. Spring Hibernate Integration Example Javaconfig
5. Serialization And Deserialization Java Example
6. Comparable And Comparator In Java With Example
7. Convert Hashmap To List Java
8. Hello World Java Program Breakup
9. Linkedlist Implementation Java
12. Pros And Cons Collection Java
Recommended
- Executorservice Tutorial
- Why Wait Notify Notifyall Defined In Object Class
- Random Password Generator Java
- Spring Hibernate Integration Example Javaconfig
- Serialization And Deserialization Java Example
- Comparable And Comparator In Java With Example
- Convert Hashmap To List Java
- Hello World Java Program Breakup
- Linkedlist Implementation Java
- Stack Implementation Java
- Tree Implementation Java
- Pros And Cons Collection Java
- Hashmap Custom Implementation Java
- Different Sorting Algorithms