Hashmap根据最大value寻找key

 
import java.util.*;

/**
 * Created by hhy on 2018/4/10.
 */
public class Test {
    public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put(1, 2);
        map.put(3, 99);
        map.put(5, 35);
        map.put(6, 19);
        int  maxNum= Integer.parseInt(gerMinValue(map).toString());
        int key = Integer.parseInt(getKey(map,maxNum).toString());
        System.out.println("最大值对应的Key"+key);
    }

    //根据最大value寻找key
    private static Object getKey(Map map,Integer value){
        int key = 0;
        for (Map.Entry entry : map.entrySet()) {
            if(value == entry.getValue()){
                key=entry.getKey();
            }
        }
        return key;
    }

    //遍历寻找最大value
    private static Object gerMinValue(Map map) {
        if (map.size() == 0)
            return null;
        Collection c = map.values();
        Object[] obj = c.toArray();
        Arrays.sort(obj);
        return obj[obj.length - 1];
    }

}







你可能感兴趣的:(程序人生)