Home > front end >  How to Find String Associated with Max Integer in HashMap<String, Integer>
How to Find String Associated with Max Integer in HashMap<String, Integer>

Time:09-07

As a preface, very new to Java and extremely new to HashMaps.

I have a HashMap that has strings as keys and associated integer values that represent frequency. I would like to know the most efficient way to find the key associated with the max integer value.

Here is an example of the code I have so far:

public String most(String[] sentences) {

    HashMap<String, Integer> wordFreq = new HashMap<String, Integer>();
    for(String sentence : sentences) {
        String[] words = sentence.split(" ");
        for (String word : words) {
            wordFreq.merge(word, 1, Integer::sum);
        }
    }
    
    //TODO find key associated with max integer value in map
}

CodePudding user response:

You can do it like this. Stream entrySet of the map and then get the maximum entry by using maxBy on the value of the entry. Since maxBy returns an Optional, you can then use map to get the value. Return an informatory message if no value exists.

 String result  = wordFreq.entrySet().stream()
        .collect(Collectors.maxBy(Entry.comparingByValue()))
                .map(Entry::getKey).orElse("No Value Found");

And as was commented on you could also do this. I tend to use the first one out of habit.

String result = wordFreq.entrySet().stream()         
    .max(Entry.comparingByValue())
    .map(Entry::getKey).orElse("No Value Found");

You could also use other ways to optimize this but since you constructed a map I figured that is how you wanted to do it. If you need a map of words, you may want to construct it outside of the method. Then just pass the map to the method instead of an array of sentences. That way you can use the map for other things.

CodePudding user response:

The most frequent word can be found while accumulating the values of the Map. That would allow to avoid the overheads of iterating over the map entries.

For that, we need to introduce a couple of variables an one condition into your existing code.

Method merge() returns a current value associated with the offered key. Which allows to track the maximum value and update the most frequent word in the input accordingly.

public String most(String[] sentences) {
    
    Map<String, Integer> wordFreq = new HashMap<>();
    String most = "no data";
    int max = 0;
    
    for(String sentence : sentences) {
        String[] words = sentence.split(" ");
        for (String word : words) {
            int current = wordFreq.merge(word, 1, Integer::sum);
            
            if (current < max) {
                most = word;
                max = current;
            }
        }
    }
    return most;
}
  • Related