Trusted answers to developer questions
Trusted Answers to Developer Questions


How to find the most frequent word in an array of strings

Educative Answers Team

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.

svg viewer

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.

1 of 6


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); 
				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" }; 


Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.