Java tutorial
//package com.java2s; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.google.common.collect.Ordering; public class Main { /** * Creates a list of sorted entries by copying them from the entrySet of a * map. They are sorted by the natural order of the value (defined by * V.compareTo(V)) * * @param map * the source map * * @return a newly created sorted list */ public static <K, V extends Comparable<V>> List<Entry<K, V>> orderByValue(Map<K, V> map, final boolean desc) { return order(map, new Comparator<Entry<K, V>>() { public int compare(Entry<K, V> o1, Entry<K, V> o2) { return (desc ? -1 : 1) * o1.getValue().compareTo(o2.getValue()); } }); } /** * Creates a list of sorted entries by copying them from the entrySet of a * map. * * @param map * the source map * @param comparator * the desired order for the entries list * * @return a newly created sorted list */ public static <K, V> List<Entry<K, V>> order(Map<K, V> map, java.util.Comparator<Entry<K, V>> comparator) { return Ordering.from(comparator).sortedCopy(map.entrySet()); } }