RSS Feed for This PostCurrent Article

Java–Sort a Map by Values

Here is a generic method to sort a Map by its values

   1: /**

   2:  * Sort a map by values

   3:  * 

   4:  * @param map Unsorted map

   5:  * @return Sorted map

   6:  */

   7: public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {

   8:     List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());

   9:     Collections.sort(list, new Comparator<Map.Entry<K, V>>() {

  10:         public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {

  11:             return (o1.getValue()).compareTo(o2.getValue());

  12:         }

  13:     });

  14:  

  15:     Map<K, V> result = new LinkedHashMap<K, V>();

  16:     for (Map.Entry<K, V> entry : list) {

  17:         result.put(entry.getKey(), entry.getValue());

  18:     }

  19:     return result;

  20: }


Trackback URL


Sorry, comments for this entry are closed at this time.