Java tutorial
//package com.java2s; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class Main { public static <E, V extends Comparable<? super V>, K> Map<K, V> sortByValueAsc(Map<K, V> map) { return sortByValueAsc(map, -1); } public static <E, V extends Comparable<? super V>, K> Map<K, V> sortByValueAsc(Map<K, V> map, int limit) { List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); Map<K, V> result = new LinkedHashMap<K, V>(); int counter = 0; for (Map.Entry<K, V> entry : list) { if (limit > 0 && counter >= limit) { break; } result.put(entry.getKey(), entry.getValue()); counter++; } return result; } public static Number getValue(Map<? extends Object, ? extends Number> map, Object key, Class<?> clazz) { Number value = map.get(key); if (value == null) { if (clazz.equals(Double.class)) { value = 0.0; } else { value = 0; } } return value; } }