🔹 Introduction
Counting character frequency is a very common Java interview question.
It tests your understanding of strings, HashMap, and Java Streams.
👉 In this article, we will cover:
- HashMap approach (most asked in interviews)
- Java Streams approach (modern & advanced)
🔹 Problem Statement
Given a string, count the occurrence of each character.
Example:
Input: aabbcc
Output: a=2, b=2, c=2
🔹 Approach 1: Using HashMap (Most Important)
💡 Explanation
- Traverse the string
- Store character count in HashMap
-
Use
getOrDefault()for clean code
👨💻 Java Code (HashMap)
import java.util.*;
public class CharacterFrequency {
public static void main(String[] args) {
String str = "aabbcc";
Map<Character, Integer> map = new HashMap<>();
for (char ch : str.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
map.forEach((key, value) ->
System.out.println(key + " = " + value)
);
}
}
🔹 Approach 2: Using Java Streams (Advanced)
💡 Explanation
- Convert string into stream of characters
-
Group characters using
groupingBy() -
Count occurrences using
counting()
👉 This is a functional programming approach
👨💻 Java Code (Streams)
import java.util.*;
import java.util.stream.*;
import java.util.function.Function;
public class CharacterFrequency {
public static void main(String[] args) {
String str = "aabbcc";
Map<Character, Long> frequencyMap =
str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
frequencyMap.forEach((key, value) ->
System.out.println(key + " = " + value));
}
}
🔍 Internal Working (Important for Interviews)
-
chars()→ converts string to IntStream -
mapToObj()→ converts int → Character -
groupingBy()→ groups same characters -
counting()→ counts frequency
🔹 Output
a = 2
b = 2
c = 2
🔹 Time Complexity
- O(n) for both approaches
🔹 HashMap vs Streams
🔹 Key Takeaways
✔ HashMap is must-know
✔ Streams show advanced skills
✔ groupingBy() is very important
🔹 Conclusion
This problem is a foundation for many string-based interview questions.
Master both approaches to stand out in interviews.
🔗 Also Read
👉 First Non-Repeating Character in Java
👉 Check Palindrome String in Java
👉 Reverse a String
Comments
Post a Comment