java中一个Map要找到值Value最小的那个元素的方法
import java.util.Arrays;
import java.util.Collection;import java.util.HashMap;import java.util.Map;import java.util.Set;public class MinMapDemo { public static void main(String[] args) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); map.put(1, 8); map.put(3, 12); map.put(5, 53); map.put(123, 33); map.put(42, 11); map.put(44, 42); map.put(15, 3); System.out.println(getMinKey(map)); System.out.println(getMinValue(map)); } /** * 求Map<K,V>中Key(键)的最小值 * @param map * @return */ public static Object getMinKey(Map<Integer, Integer> map) { if (map == null) return null; Set<Integer> set = map.keySet(); Object[] obj = set.toArray(); Arrays.sort(obj); return obj[0]; } /** * 求Map<K,V>中Value(值)的最小值 * @param map * @return */ public static Object getMinValue(Map<Integer, Integer> map) { if (map == null) return null; Collection<Integer> c = map.values(); Object[] obj = c.toArray(); Arrays.sort(obj); return obj[0]; }}
浙公网安备 33010602011771号