Skip to content

Instantly share code, notes, and snippets.

@friek
Last active December 17, 2015 00:38
Show Gist options
  • Select an option

  • Save friek/5522195 to your computer and use it in GitHub Desktop.

Select an option

Save friek/5522195 to your computer and use it in GitHub Desktop.
Sort a map by value.
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Shamelessly stolen from
* http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java/2581754#2581754
*/
public class SortMap
{
/**
* Sort a map by value descending.
* @param map
* @return
*/
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDescending(Map<K, V> map)
{
return sortByValue(map, true);
}
/**
* Sort a map by value ascending.
* @param map
* @return
*/
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map)
{
return sortByValue(map, false);
}
/**
* Sort a map by value.
* @param map
* @param descending Set to true to sort descending.
* @return
*/
private static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean descending)
{
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>()
{
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// Descending if requested.
if (descending)
Collections.reverse(list);
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list)
result.put(entry.getKey(), entry.getValue());
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment