Count Word Frequency Using HashMap

Java coding interview problem for Collections: Count Word Frequency Using HashMap.

Counting the frequency of words is one of the most common problems used to introduce HashMap-based problem solving.

This problem teaches an important pattern:

Input Data

      ↓

Extract Elements

      ↓

Store Count Using HashMap

      ↓

Process Frequency

Frequency counting is widely used in:

  • Text processing
  • Search engines
  • Data analytics
  • Log analysis
  • Natural language processing

What is Word Frequency Counting?

Word frequency counting means finding how many times each word appears in a given text.


Example

Input:

java spring boot java spring

Frequency:

java  → 2

spring → 2

boot → 1

Why Do We Need Frequency Counting?

Many real-world systems need to know:

  • Most common words
  • Duplicate values
  • Popular searches
  • Repeated events
  • User activity patterns

Real-World Applications

Search Engines

Search engines analyze:

Keyword Frequency

to understand document relevance.


Log Analysis

Production systems analyze:

ERROR

WARNING

INFO

frequency counts.

Example:

ERROR = 120

WARNING = 40

Data Analytics

Companies analyze:

  • Customer feedback
  • Reviews
  • Surveys

to find frequently used terms.


Natural Language Processing

NLP systems calculate:

  • Word frequency
  • Term importance
  • Text similarity

Understanding HashMap

A HashMap stores data as:

Key → Value

Example:

Word → Count

HashMap:

java   → 2

spring → 2

boot   → 1

HashMap Structure

Internally:

HashMap

    |
    |
 Buckets

    |
    |
 Nodes

(key,value)

Example:

HashMap

Bucket 0

Bucket 1
    |
    |
 ("java",2)

Bucket 2
    |
    |
 ("spring",2)

Key-Value Pair Concept

A word becomes:

Key

The frequency becomes:

Value

Example:

Input:

java java spring

Processing:

First java:

java → 1

Second java:

java → 2

Spring:

spring → 1

Why HashMap is Used for Frequency Counting?

Because HashMap provides:

Fast Lookup

Average:

O(1)

for:

  • Insert
  • Search
  • Update

Example:

Without HashMap:

Find existing word:

Scan all previous words

Complexity:

O(n²)

With HashMap:

Check key:

O(1)

HashMap Internal Working

When inserting:

map.put("java", 1);

Java performs:

java

   ↓

hashCode()

   ↓

Bucket calculation

   ↓

Store key-value pair

Hash Function Concept

Every key generates:

hashCode()

Example:

"java"

     ↓

123456

This determines bucket location.


Collision Handling

Sometimes:

Two keys produce the same bucket.

Example:

Word A

     ↓

Bucket 5


Word B

     ↓

Bucket 5

This is called:

Collision

Java HashMap handles collisions using:

  • Linked List
  • Tree structure (after threshold)

Problem Statement

Given a string containing multiple words, count the frequency of each word.

Return:

word → count

Example 1

Input:

apple banana apple orange banana apple

Output:

apple  → 3

banana → 2

orange → 1

Example 2

Input:

java spring java boot spring java

Output:

java   → 3

spring → 2

boot   → 1

Constraints

Example:

1 <= number of words <= 100000

Frequency Counting Visualization

Input:

cat dog cat bird dog cat

Start:

{}

Read:

cat

Map:

cat → 1

Read:

dog

Map:

cat → 1

dog → 1

Read:

cat

Update:

cat → 2

Final:

cat  → 3

dog  → 2

bird → 1

Approach 1 — Brute Force Approach

The simplest approach:

For every word:

  1. Search existing list.
  2. If found, increase count.
  3. Otherwise add new word.

Example

Input:

java spring java

Process:

First:

java

Store:

java → 1

Second:

spring

Store:

spring → 1

Third:

java

Search previous words.

Found:

java

Update:

java → 2

Brute Force Java Program

import java.util.*;

public class WordFrequencyBruteForce {


    public static Map<String,Integer> countWords(
            String sentence) {


        Map<String,Integer> result =
                new HashMap<>();


        String[] words =
                sentence.split(" ");


        List<String> processed =
                new ArrayList<>();


        for(String word : words) {


            if(!processed.contains(word)) {


                int count = 0;


                for(String current : words) {


                    if(current.equals(word)) {

                        count++;

                    }

                }


                result.put(
                        word,
                        count);


                processed.add(word);

            }

        }


        return result;

    }

}

Complexity Analysis — Brute Force

For:

n words

For each word:

Search all words.

Time:

O(n²)

Space:

O(n)

Drawbacks of Brute Force

  • Slow for large input.
  • Repeated comparisons.
  • Does not use efficient lookup.

Approach 2 — HashMap Frequency Counting

The optimized approach uses:

HashMap<String,Integer>

Algorithm

  1. Split sentence into words.
  2. Traverse every word.
  3. Store count in HashMap.

Logic:

If word exists:

increase count

Otherwise:

insert count = 1

Java Program — HashMap Approach

import java.util.HashMap;
import java.util.Map;

public class WordFrequencyHashMap {


    public static Map<String,Integer> countWords(
            String sentence) {


        Map<String,Integer> frequency =
                new HashMap<>();


        String[] words =
                sentence.split(" ");


        for(String word : words) {


            frequency.put(
                    word,
                    frequency.getOrDefault(
                            word,
                            0) + 1);

        }


        return frequency;

    }


    public static void main(String[] args) {


        String text =
                "java spring java boot spring java";


        System.out.println(
                countWords(text));

    }

}

Output

{
java=3,
spring=2,
boot=1
}

Step-by-Step Explanation

Input:

java spring java boot spring java

Initial:

{}

Read:

java

Add:

java=1

Read:

spring

Add:

spring=1

Read:

java

Update:

java=2

Read:

boot

Add:

boot=1

Read:

spring

Update:

spring=2

Read:

java

Update:

java=3

Final:

java=3

spring=2

boot=1

Complexity Analysis

For:

n words

Each HashMap operation:

O(1)

Total:

Time:

O(n)

Space:

O(k)

where:

k = unique words

Advantages

  • Very fast.
  • Simple implementation.
  • Scales for large input.
  • Standard interview solution.

Drawbacks

  • HashMap does not maintain order.
  • Requires additional memory.

Java 8 getOrDefault() Method

The getOrDefault() method is one of the most commonly used HashMap methods for frequency counting.

Syntax:

map.getOrDefault(key, defaultValue)

How getOrDefault Works

Example:

frequency.put(
    word,
    frequency.getOrDefault(word,0)+1
);

First occurrence:

Input:

java

Map:

{}

Check:

java exists?

No.

Return:

0

Update:

java = 1

Second occurrence:

java

Map:

java = 1

Return:

1

Update:

java = 2

Using Java 8 merge() Method

Java provides another cleaner approach:

map.merge(
    word,
    1,
    Integer::sum
);

How merge Works

Syntax:

map.merge(key, value, function)

If key does not exist:

Insert:

key → value

If key exists:

Apply:

function

Example:

Input:

java java spring

First:

java → 1

Second:

java → 2

Spring:

spring → 1

Java Program Using merge()

import java.util.HashMap;
import java.util.Map;

public class WordFrequencyMerge {


    public static Map<String,Integer> countWords(
            String sentence) {


        Map<String,Integer> map =
                new HashMap<>();


        for(String word :
                sentence.split(" ")) {


            map.merge(
                    word,
                    1,
                    Integer::sum);

        }


        return map;

    }

}

Using Java Streams and Collectors

Java Streams provide a functional approach.


Example:

Input:

java spring java boot spring

Convert:

Stream<String>

Group:

Collectors.groupingBy()

Count:

Collectors.counting()

Java Streams Program

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class WordFrequencyStreams {


    public static Map<String, Long> countWords(
            String sentence) {


        return Arrays.stream(
                    sentence.split(" "))
                .collect(
                    Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()
                    )
                );

    }

}

Output

Input:

java spring java boot spring

Output:

{
java=2,
spring=2,
boot=1
}

Sorting Words by Frequency

HashMap does not maintain order.

Example:

java=3

spring=2

boot=1

If we want:

highest frequency first

we need sorting.


Approach

  1. Convert Map entries to List.
  2. Sort by value.
  3. Collect result.

Java Program

import java.util.*;

public class SortFrequency {


    public static List<Map.Entry<String,Integer>>
    sortByFrequency(
            Map<String,Integer> map) {


        List<Map.Entry<String,Integer>> list =
                new ArrayList<>(
                    map.entrySet()
                );


        list.sort(
            (a,b) ->
                b.getValue()
                 -
                a.getValue()
        );


        return list;

    }

}

Output Example

Input:

java=3

spring=2

boot=1

Sorted:

java=3

spring=2

boot=1

Finding Most Frequent Word

A common interview variation:

Find the word with maximum frequency.


Algorithm

  1. Count frequencies.
  2. Track maximum count.
  3. Return corresponding word.

Java Program

public class MostFrequentWord {


    public static String findMostFrequent(
            Map<String,Integer> map) {


        String result = "";

        int max = 0;


        for(Map.Entry<String,Integer> entry :
                map.entrySet()) {


            if(entry.getValue() > max) {


                max =
                entry.getValue();


                result =
                entry.getKey();

            }

        }


        return result;

    }

}

Case Insensitive Frequency Counting

Problem:

Input:

Java JAVA java

Should output:

java = 3

Solution

Convert every word to lowercase.

word = word.toLowerCase();

Java Example

for(String word :
        sentence.split(" ")) {


    word =
        word.toLowerCase();


    map.put(
        word,
        map.getOrDefault(word,0)+1
    );

}

Handling Special Characters

Input:

hello, world! hello.

Problem:

Words become:

hello,

world!

hello.

Different keys.


Solution

Remove special characters.

Example:

word.replaceAll(
    "[^a-zA-Z]",
    ""
);

Example

Before:

hello,

hello!

After:

hello

hello

Frequency:

hello = 2

Word Frequency in Large Files

For large files:

GB/TB data

loading everything into memory is not recommended.


Better Approach

Process file line by line:

Read Line

↓

Split Words

↓

Update HashMap

↓

Continue

Java File Processing Example

BufferedReader reader =
    new BufferedReader(
        new FileReader("file.txt")
    );


String line;


while((line = reader.readLine())
        != null) {


    for(String word :
            line.split(" ")) {


        map.put(
            word,
            map.getOrDefault(word,0)+1
        );

    }

}

HashMap vs LinkedHashMap vs TreeMap

Feature HashMap LinkedHashMap TreeMap
Ordering No order Insertion order Sorted order
Performance O(1) O(1) O(log n)
Internal Structure Hash Table Hash Table + Linked List Red Black Tree
Use Case Fast lookup Maintain order Sorted keys

Example

HashMap

Output:

boot
java
spring

Order not guaranteed.


LinkedHashMap

Output:

java
spring
boot

Insertion order preserved.


TreeMap

Output:

boot
java
spring

Alphabetical order.


Custom Object Frequency Counting

HashMap is not limited to Strings.

Example:

Count employee occurrences:

Map<Employee,Integer> count =
        new HashMap<>();

Example:

Employee Object

       ↓

Frequency

Employee Class

class Employee {

    int id;

    String name;


    Employee(int id,String name){

        this.id=id;

        this.name=name;

    }


}

For custom objects:

Override:

equals()

hashCode()

Primitive vs Object Collections

Java Collections do not support primitives.

Cannot:

HashMap<int,int>

Use:

HashMap<Integer,Integer>

Because:

int

↓

Integer

boxing occurs.


Common Interview Mistakes

Mistake 1

Using nested loops.

Wrong complexity:

O(n²)

Mistake 2

Ignoring case sensitivity.

Example:

Java

java

may become different keys.


Mistake 3

Not cleaning punctuation.

Example:

hello

hello!

Mistake 4

Using HashMap when sorted output is required.

Use:

TreeMap

or sorting.


Edge Cases

Case Expected Result
Empty string Empty map
Single word Count = 1
Duplicate words Correct count
Different cases Normalize
Special characters Clean input
Large file Stream processing

Interview Follow-up Questions

Q1. Count word frequency using HashMap.

Q2. Find most frequent word.

Q3. Find top K frequent words.

Q4. Sort words by frequency.

Q5. Count character frequency.

Q6. Count frequency from a file.

Q7. Find duplicate words.

Q8. Group words by frequency.


Related HashMap Problems

  • Two Sum
  • First Non-Repeating Character
  • Group Anagrams
  • Top K Frequent Elements
  • Longest Consecutive Sequence
  • Subarray Sum Equals K
  • Majority Element

Key Takeaways

Word frequency counting follows a common HashMap pattern:

Read Element

      ↓

Check Existing Key

      ↓

Increase Count

      ↓

Store Result

The preferred approaches:

getOrDefault()

or

merge()

Complexity:

Time: O(n)

Space: O(k)

where:

k = unique words

Frequently Asked Interview Questions

Q1. Why use HashMap?

Because lookup and update are average:

O(1)

Q2. Difference between HashMap and TreeMap?

HashMap:

Fast lookup

TreeMap:

Sorted order

Q3. How to handle uppercase/lowercase?

Normalize:

toLowerCase()

Q4. How to handle punctuation?

Use:

replaceAll()

Interview Tip

When asked:

"Count frequency of words."

Explain:

  1. Split input into words.
  2. Use HashMap.
  3. Store word as key.
  4. Store count as value.
  5. Discuss edge cases.

For senior interviews, mention:

  • HashMap internals.
  • Collision handling.
  • Large file processing.
  • Stream-based processing.

This demonstrates strong understanding of Java Collections and frequency-based problem solving.