Finding the key of HashMap which holds the lowest integer value

后端 未结 5 833
暖寄归人
暖寄归人 2021-01-21 21:07

I\'m creating an educational game for young students who needs to learn the most common words. On random I pick three words of the list, show them on the screen, play an audio r

5条回答
  •  抹茶落季
    2021-01-21 21:50

    This is a variation of the answer of user3309578 static HashMap words = new HashMap();

    private static String getMax () {
        String minKey = null;
        int minValue = Integer.MAX_VALUE;
        for (String key : words.keySet()) {
            int value = words.get(key);
            if (value < minValue) {
                minValue = value;
                minKey = key;
            }
        }
        return minKey;
    }
    
    public static void main (String[] args) {
        words.put("a", 2);
        words.put("b", 4);
        words.put("c", 6);
        words.put("d", 8);
        words.put("e", 1);
        words.put("f", 3);
        words.put("g", 5);
        words.put("h", 7);
        System.out.println(getMax());
    }
    

提交回复
热议问题