Finding the key of HashMap which holds the lowest integer value

21,995

Solution 1

What about this?

private String getMinKey(Map<String, Integer> map, String... keys) {
    String minKey = null;
    int minValue = Integer.MAX_VALUE;
    for(String key : keys) {
        int value = map.get(key);
        if(value < minValue) {
            minValue = value;
            minKey = key;
        }
    }
    return minKey;
}

Solution 2

Possibly the shortest solution, with Java 8:

private String getMinKey(Map<String, Integer> map, String... keys) {

    return map.entrySet().stream()
     .filter(p -> Arrays.asList(keys).contains(p.getKey()))
     .min(Comparator.comparingInt(Map.Entry::getValue)).get().getKey();

}

Solution 3

First get the entry set from the map:

Set<Entry<String,Integer>> entries = map.entrySet();

Now dump that into an ArrayList so you can sort it:

List<Entry<String,Integer>> sortedEntries = new ArrayList<>(entries);

Now sort the list:

Collections.sort(sortedEntries, /*Define your comparitor here to compare by values */);

Your list now has the contents of the map sorted by value, you can access them in whatever order you like.

Solution 4

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());
}
Share:
21,995
Cyberlurk
Author by

Cyberlurk

Updated on January 21, 2021

Comments

  • Cyberlurk
    Cyberlurk over 3 years

    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 recording of one of the three words and then the student has to pick the word that has been pronounced. I keep track of how many times they have guessed each word. In that way I can set up a criteria for when new words should be introduced to the student. When three of the words are picked I'll like to pronounce the word that the student has had least exposure to.

    I have a HashMap called words, which contains the words, and a integer value of how many times the student guessed the word.

      HashMap<String,Integer>  words 
    

    It contains between 10 - 120 keys/words. I'll like to create a method, which takes three of the hash map keys as parameters, that can return the String/key having the lowest value of the keys asked for.

    I have had trouple getting this to work as intended and I'd appreciate any help.