Java Tutorial
🔍
What is OOP?Classes & ObjectsConstructorsAccess Modifiersthis Keywordstatic KeywordEncapsulationInheritancesuper KeywordMethod OverridingOverloading vs OverridingPolymorphismUpcasting & Downcastinginstanceof OperatorAbstractionAbstract ClassesInterfacesMarker InterfacesAbstract Class vs InterfaceObject ClasstoString() Methodequals() & hashCode()
Collections OverviewCollections HierarchyIterable InterfaceCollection InterfaceMap Interfaceequals() and hashCode()IteratorListIteratorFail-fast vs Fail-safe IteratorConcurrentModificationExceptionArrayListLinkedListHashSetLinkedHashSetTreeSetQueuePriorityQueueDequeArrayDequeHashMapLinkedHashMapTreeMapConcurrentHashMapCopyOnWriteArrayListList vs Set vs MapChoosing the Right CollectionComparableComparatorComparable vs ComparatorCollections Utility ClassArrays Utility ClassImmutable CollectionsCollection vs CollectionsVectorHashtableStackArrayList Internal WorkingLinkedList Internal WorkingHashMap Internal WorkingTreeMap Internal Working
Word Frequency with HashMap in Java
intermediate· Collections · Map
Problem
A HashMap stores key-value pairs, making it a natural fit for counting how often each item in a collection appears.
Given a sentence, count how many times each word appears.
Input
"the quick fox the lazy fox the dog"
Output
the: 3, quick: 1, fox: 2 ...
Java Program
Java
import java.util.HashMap;
import java.util.Map;
public class WordFrequency {
public static void main(String[] args) {
String text = "the quick fox the lazy fox the dog";
Map<String, Integer> freq = new HashMap<>();
for (String word : text.split(" ")) {
// getOrDefault(word, 0) reads the current count, or 0 if unseen, then increments it
freq.put(word, freq.getOrDefault(word, 0) + 1);
}
for (Map.Entry<String, Integer> entry : freq.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}Output
the: 3
quick: 1
fox: 2
lazy: 1
dog: 1
Core Logic
A HashMap makes this straightforward — split the sentence into words and bump each word's count as you go.
How It Works
- 1
text.split(" ")breaks the sentence into individual words. - 2A
HashMap<String, Integer>tracks each word's running count. - 3
freq.getOrDefault(word, 0)reads the current count, or0if the word hasn't been seen yet. - 4Adding
1and callingfreq.put(word, ...)stores the updated count in one line. - 5
entrySet()is iterated afterward to print every word alongside its final count.
In
"the quick fox the lazy fox the dog", "the" ends with a count of 3 and "fox" ends with a count of 2.💡
Key Point: getOrDefault() removes the need for a separate 'does this key exist yet' check before incrementing.
Key Concepts
HashMapgetOrDefault()entrySet()
Approach 2: Streams + Collectors.groupingBy()
Java
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class WordFrequencyStream {
public static void main(String[] args) {
String text = "the quick fox the lazy fox the dog";
// Groups equal words together and counts how many are in each group
Map<String, Long> freq = Arrays.stream(text.split(" "))
.collect(Collectors.groupingBy(word -> word, Collectors.counting()));
freq.forEach((word, count) -> System.out.println(word + ": " + count));
}
}
Output
the: 3
quick: 1
fox: 2
lazy: 1
dog: 1
Core Logic
Streams can express the same idea more declaratively — groupingBy plus counting() builds the frequency map in one line.
How It Works
- 1
Arrays.stream(text.split(" "))turns the split words into aStream<String>. - 2
Collectors.groupingBy(word -> word, Collectors.counting())groups equal words together and counts how many are in each group. - 3The result is a
Map<String, Long>— note the count is aLong, not anint, sincecounting()always produces one. - 4
freq.forEach((word, count) -> ...)prints every entry using a lambda instead of an explicitentrySet()loop.
Grouping
"the quick fox the lazy fox the dog" produces the same counts as the manual version: the: 3, fox: 2, quick: 1, lazy: 1, dog: 1.💡
Key Point: groupingBy + counting() is the idiomatic modern-Java way to build a frequency map — it reads as 'group by identity, then count', with no manual increment logic at all.
Key Concepts
StreamCollectors.groupingBy()Collectors.counting()