Advertisement
jaVer404

Sort HashMap by VALUE

Jan 15th, 2016
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.03 KB | None | 0 0
  1.     public static HashMap<String, String> sortByComparator(Map<String, String> unsortMap) {
  2.         // Convert Map to List
  3.         List<Map.Entry<String, String>> list =
  4.                 new LinkedList<Map.Entry<String, String>>(unsortMap.entrySet());
  5.         // Sort list with comparator, to compare the Map values
  6.         Collections.sort
  7.                 (list, new Comparator<Map.Entry<String, String>>() {
  8.                     public int compare(Map.Entry<String, String> o1,
  9.                                        Map.Entry<String, String> o2) {
  10.                         return (o1.getValue()).compareTo(o2.getValue());
  11.                     }
  12.                 });
  13.         // Convert sorted map back to a Map
  14.         HashMap<String, String> sortedMap = new LinkedHashMap<String, String>();
  15.         for (Iterator<Map.Entry<String, String>> it = list.iterator(); it.hasNext();) {
  16.             Map.Entry<String, String> entry = it.next();
  17.             sortedMap.put(entry.getKey(), entry.getValue());
  18.         }
  19.         return sortedMap;
  20.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement