Given an array of strings, one must find the most frequent word in a given array, i.e., the string that appears the most in the array. If there is a tie or all strings have the same frequency, ​the string that is the smallest (lexicographically) ​is printed.
The most efficient approach to this problem is to use HashMap. We will insert all the unique strings in the map and update the count every-time the same string appears in the array.
In the code below, a hashmap is used to store and keep track of the strings in the array.
// Java program import java.util.*; class MostFrequentWord { // Function to calculate the most frequent word in the array. public static void FrequentWord(String array[]) { // Insert all unique strings and update count if a string is not unique. Map<String,Integer> hshmap = new HashMap<String, Integer>(); for (String str : array) { if (hshmap.keySet().contains(str)) // if already exists then update count. hshmap.put(str, hshmap.get(str) + 1); else hshmap.put(str, 1); // else insert it in the map. } // Traverse the map for the maximum value. String maxStr = ""; int maxVal = 0; for (Map.Entry<String,Integer> entry : hshmap.entrySet()) { String key = entry.getKey(); Integer count = entry.getValue(); if (count > maxVal) { maxVal = count; maxStr = key; } // Condition for the tie. else if (count == maxVal){ if (key.length() < maxStr.length()) maxStr = key; } } System.out.println("Most frequent word: "+ maxStr); System.out.println("Count: "+ maxVal); } // Main public static void main(String[] args) { String[] arr = { "Batman", "Thor", "Batman" , "Flash", "Batman" }; FrequentWord(arr); } }
RELATED TAGS
View all Courses