Introduction

Counting word frequency is essential for text analysis, NLP, and data mining applications.


Method 1: Using HashMap

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

public class WordFrequency {
    
    public static Map<String, Integer> getWordFrequency(String sentence) {
        Map<String, Integer> frequency = new HashMap<>();
        
        if (sentence == null || sentence.isEmpty()) {
            return frequency;
        }
        
        String[] words = sentence.toLowerCase().split(" ");
        
        for (String word : words) {
            frequency.put(word, frequency.getOrDefault(word, 0) + 1);
        }
        
        return frequency;
    }
    
    public static void main(String[] args) {
        String sentence = "hello world hello java world";
        Map<String, Integer> frequency = getWordFrequency(sentence);
        
        frequency.forEach((word, count) -> 
            System.out.println(word + ": " + count)
        );
    }
}

Output:

hello: 2
world: 2
java: 1

Method 2: Using LinkedHashMap (Preserves Order)

import java.util.LinkedHashMap;
import java.util.Map;

public class WordFrequencyOrdered {
    
    public static Map<String, Integer> getWordFrequency(String sentence) {
        Map<String, Integer> frequency = new LinkedHashMap<>();
        
        String[] words = sentence.toLowerCase().split(" ");
        
        for (String word : words) {
            frequency.put(word, frequency.getOrDefault(word, 0) + 1);
        }
        
        return frequency;
    }
}

Method 3: Using Streams

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

public class WordFrequencyStream {
    
    public static Map<String, Long> getWordFrequency(String sentence) {
        return Arrays.stream(sentence.toLowerCase().split(" "))
                    .collect(Collectors.groupingBy(
                        word -> word,
                        Collectors.counting()
                    ));
    }
}

Frequently Asked Questions

Q1. Should I remove punctuation?

Answer: Yes, before counting for accuracy.

Advertisement

Q2. Case sensitivity?

Answer: Convert to lowercase for combined count.

Q3. Stop words?

Answer: Filter against a stop words list.

Q4. Performance?

Answer: HashMap is O(n), Streams similar.

Q5. Sort by frequency?

Answer: Use TreeMap or sort the entrySet.

Q6. Large text files?

Answer: Streams scale better with memory.

Q7. Minimum frequency threshold?

Answer: Filter:

f.entrySet().stream().filter(e -> e.getValue() >= min)

Q8. Find most frequent?

Answer: Use max() by count.

Q9. Unicode support?

Answer: Yes, all methods support Unicode.

Q10. Export results?

Answer: Convert to JSON or CSV format.


Conclusion

HashMap is most direct approach. Streams better for complex processing. Choose based on requirements.