Java Map 中获取最大值 Value 和对应的 Key
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class e {
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:" + getKeyStr(map));
}
private static String getKeyStr(Map<String, Object> map) {
int maxV = 0;
String maxK;
//临时值,保存每次最大值键,下个值比他大就将他替掉,换成新值
String maxKRemove = null;
Map<String, Object> map2 = new TreeMap();
for (Map.Entry<String, Object> entry : map.entrySet()) {
maxK = entry.getKey();
int value = Integer.parseInt(entry.getValue().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);
}
}
String strKey = "";
int value = 0;
for (Map.Entry<String, Object> entry : map2.entrySet()) {
maxK = entry.getKey();
value = Integer.parseInt(entry.getValue().toString());
String[] maxKey = maxK.split("_");
strKey = maxKey[0];
}
System.out.println("Key:" + strKey + ",Value:" + value);
return strKey;
}
}