Java Program to Sort a HashMap by Keys and Values
HashMap<K, V> is a Java Collection and is a part of java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in the form of Key, Value pairs, where the keys must be unique but there is no restriction for values. If we try to insert the duplicate key, it will replace the element of the corresponding key.
HashMap Sorting by Values
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
The idea is to store the entry set in a list and then sort the list based on values using the Collections.sort() method with the help of Comparator. Then fetch the value for each key from the list and then display the result.
Key : zero, Value : 0 Key : three, Value : 3 Key : five, Value : 5 Key : seven, Value : 7 Key : eight, Value : 8 Key : nine, Value : 9
HashMap Sorting by Keys
The idea is to put all data of HashMap into an ArrayList.Then extract all the keys of HashMap into an ArrayList. Next, sort the extracted keys using the Collections.sort() method, and then for each key extract its value using the get() method. Finally, the map is sorted according to its keys.
Key = 1, Value = one Key = 3, Value = three Key = 5, Value = five Key = 7, Value = seven Key = 9, Value = nine