InterviewSolution
Saved Bookmarks
| 1. |
Write a program to sort a map based on value? |
|
Answer» You can see the below code snippet: // class to sort hashmap by values public class SortByValue{ public static HashMap<String, Integer> sortByValue (HashMap<String, Integer> hm) { List<MAP.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet()); 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()); } }); HashMap<String, Integer> tempMap = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> element : list) { tempMap.put(element.getKey(), element.getValue()); } return tempMap; } // Driver Code public static void main(String[] args) { HashMap<String, Integer> hm = new HashMap<String, Integer>(); // enter DATA into hashmap hm.put("COMPUTER Science", 93); hm.put("Physics", 88); hm.put("Chemistry", 69); hm.put("Database", 95); hm.put("Operating System", 90); hm.put("Networking", 79); Map<String, Integer> map = sortByValue(hm); // print the sorted hashmap for (Map.Entry<String, Integer> en : map.entrySet()) { System.out.println("Key = " + en.getKey() + ", Value = " + en.getValue()); } } } |
|