Java Map 中获取最大值 Value 和对应的 Key
案例如下
import java.util.*;
public class MaxMapDemo {
public static void main(String[] args) {
Map<String, Object> map = new HashMap();
map.put("张三", 28);
map.put("李四", 18);
map.put("王五", 8);
System.out.println("Map中Value(值)的最大值的Key:" + getMaxStr(map));
}
public static String getMaxStr(Map<String, Object> map) {
int maxV = 0;
String maxK = null;
//临时值,保存每次最大值键,下个值比他大就将他替掉,换成新值
String maxKRemove = null;
Map<String, Object> map2 = new TreeMap();
Iterator keys = map.keySet().iterator();
while (keys.hasNext()) {
Object key = keys.next();
maxK = key.toString();
int value = Integer.parseInt(map.get(key).toString());
if (value > maxV) {
if (null != maxKRemove) {
map2.clear();
}
maxV = value;
map2.put(maxK, maxV);
maxKRemove = maxK;
} else if (value == maxV) {
map2.put(maxK, maxV);
}
}
Iterator keys2 = map2.keySet().iterator();
String strKey = "";
int value = 0;
while (keys2.hasNext()) {
Object key = keys2.next();
maxK = key.toString();
value = Integer.parseInt(map.get(key).toString());
String[] maxKey = maxK.split("_");
strKey = maxKey[0];
}
System.out.println("Key:" + strKey + ",Value:" + value);
return strKey;
}
输出的结果
Key:张三,Value:28
Map中Value(值)的最大值的Key:张三