Given marks scored out of 100 by a student in subjects where name of the subject is key and marks scored is the value. Our task is to sort the hashmap according to values i.e. according to marks.
Example:
Input : Key = Math, Value = 98 Key = Data Structure, Value = 85 Key = Database, Value = 91 Key = Java, Value = 95 Key = Operating System, Value = 79 Key = Networking, Value = 80 Output : Key = Operating System, Value = 79 Key = Networking, Value = 80 Key = Data Structure, Value = 85 Key = Database, Value = 91 Key = Java, Value = 95 Key = Math, Value = 98
Solution: The idea is to store the entry set in a list and sort the list on the basis of values. Then fetch values and keys from list and put them in new hashmap. Thus new hashmap is sorted according to values.
Below is implementation of the above idea:
// Java program to sort hashmap by values import java.util.*; import java.lang.*; public class GFG { // function to sort hashmap by values public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // put data from sorted list to hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } // Driver Code public static void main(String[] args) { HashMap<String, Integer> hm = new HashMap<String, Integer>(); // enter data into hashmap hm.put( "Math" , 98 ); hm.put( "Data Structure" , 85 ); hm.put( "Database" , 91 ); hm.put( "Java" , 95 ); hm.put( "Operating System" , 79 ); hm.put( "Networking" , 80 ); Map<String, Integer> hm1 = sortByValue(hm); // print the sorted hashmap for (Map.Entry<String, Integer> en : hm1.entrySet()) { System.out.println( "Key = " + en.getKey() + ", Value = " + en.getValue()); } } } |
Output:
Key = Operating System, Value = 79 Key = Networking, Value = 80 Key = Data Structure, Value = 85 Key = Database, Value = 91 Key = Java, Value = 95 Key = Math, Value = 98
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.