InterviewSolution
Saved Bookmarks
| 1. |
Sort a HashMap according to values in Java |
|
Answer» A method is created to sort the HashMap according to VALUE. The HashMap contains the names of 5 students as the key and their average marks as the value. Therefore, the HashMap is sorted according to the marks obtained by the students. A program that demonstrates this is given as follows: import java.util.*; import java.lang.*; public class Example { public static HashMap<String, Integer> sortHashMapByValue(HashMap<String, Integer> studentDetails) { List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(studentDetails.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() { public int compare(Map.Entry<String, Integer> val1, Map.Entry<String, Integer> val2) { return (val1.getValue()).COMPARETO(val2.getValue()); } }); HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> i : list) { temp.put(i.getKey(), i.getValue()); } return temp; } public static VOID main(String[] args) { HashMap<String, Integer> studentDetails = new HashMap<String, Integer>(); studentDetails.put("AMY", 56); studentDetails.put("John", 99); studentDetails.put("Peter", 25); studentDetails.put("Susan", 85); studentDetails.put("Harry", 68); System.out.println("Original HashMap"); for (Map.Entry<String, Integer> i : studentDetails.entrySet()) { System.out.println("Key = " + i.getKey() + ", Value = " + i.getValue()); } Map<String, Integer> sortedStudentDetails = sortHashMapByValue(studentDetails); System.out.println("\nSorted HashMap"); for (Map.Entry<String, Integer> i : sortedStudentDetails.entrySet()) { System.out.println("Key = " + i.getKey() + ", Value = " + i.getValue()); } } }The output of the above program is as follows: Original HashMap Key = Harry, Value = 68 Key = Susan, Value = 85 Key = John, Value = 99 Key = Peter, Value = 25 Key = Amy, Value = 56 Sorted HashMap Key = Peter, Value = 25 Key = Amy, Value = 56 Key = Harry, Value = 68 Key = Susan, Value = 85 Key = John, Value = 99 |
|