Java String Program · S06
Count Occurrence of Each Character in Java
Build a frequency table for a string: every character mapped to how many times it appears. It is the starting point for anagram, duplicate and first-unique-character questions.
Problem Statement
Write a method that returns how many times each character appears in a string. Spaces are skipped, and the comparison is case-sensitive, so a and A are counted separately.
Return the counts in the order in which each character first appears. An empty string returns an empty map.
Input/Output Examples
"banana"Output{b=1, a=3, n=2}Explanation: a appears three times and n twice; b comes first because it appears first."a b A"Output{a=1, b=1, A=1}Explanation: the spaces are skipped, and a and A are different characters.""Output{}Explanation: there are no characters to count.Visual Explanation
"banana": a new character is added with count 1 (purple), and a repeated character increases its existing count (amber).Each character is looked up in the map once. merge(c, 1, Integer::sum) inserts 1 for a new key or adds 1 to the existing value, so one line handles both cases.
Approaches
Both approaches build the same map. One uses a plain loop, the other a stream collector.
Approach 1: LinkedHashMap With merge() (Recommended)
Idea: walk the string and update a LinkedHashMap, which keeps keys in the order they were first inserted.
- Create an empty
LinkedHashMap<Character, Integer>. - For each character that is not a space, call
counts.merge(c, 1, Integer::sum). - Return the map.
Time: O(n) · Space: O(k).
Approach 2: Streams and groupingBy()
Idea: turn the string into a stream of characters, group equal characters together and count each group.
- Stream the characters with
chars()and filter out spaces. - Box each
intinto aCharacterwithmapToObj(). - Collect with
groupingBy(identity, LinkedHashMap::new, counting()).
Time: O(n) · Space: O(k).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: LinkedHashMap With merge() (Recommended)
A HashMap would also count correctly, but its iteration order is not guaranteed. LinkedHashMap keeps the first-appearance order shown in the output.
import java.util.LinkedHashMap;
import java.util.Map;
public class CharFrequencyMap {
// Counts each character except spaces, in order of first appearance
static Map<Character, Integer> countChars(String text) {
Map<Character, Integer> counts = new LinkedHashMap<>();
for (char c : text.toCharArray()) {
if (c != ' ') {
counts.merge(c, 1, Integer::sum);
}
}
return counts;
}
public static void main(String[] args) {
String[] inputs = {"banana", "a b A", ""};
for (String text : inputs) {
System.out.println("\"" + text + "\" -> " + countChars(text));
}
}
}
"banana" -> {b=1, a=3, n=2}
"a b A" -> {a=1, b=1, A=1}
"" -> {}
Time complexity: O(n) · Space complexity: O(k).
Approach 2: Streams and groupingBy()
One expression builds the map. The values are Long because Collectors.counting() returns a long count.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CharFrequencyStream {
// Groups the characters and counts each group; LinkedHashMap keeps first-seen order
static Map<Character, Long> countChars(String text) {
return text.chars()
.filter(c -> c != ' ')
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
}
public static void main(String[] args) {
String[] inputs = {"banana", "a b A", ""};
for (String text : inputs) {
System.out.println("\"" + text + "\" -> " + countChars(text));
}
}
}
"banana" -> {b=1, a=3, n=2}
"a b A" -> {a=1, b=1, A=1}
"" -> {}
Time complexity: O(n) · Space complexity: O(k).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| LinkedHashMap With merge() | O(n) | O(k) |
| Streams and groupingBy() | O(n) | O(k) |
Here n is the length of the string and k is the number of distinct characters, which is at most n. Each map update takes O(1) time on average.
Interview Tips and Recommended Approach
- Choose the map deliberately. Say why you use
LinkedHashMap(first-seen order) instead ofHashMap(no order) orTreeMap(sorted order). - Know
merge()andgetOrDefault(). Both replace the oldif (map.containsKey(c))pattern with one clear line. - Mention the array alternative. For lowercase letters only, an
int[26]counter is faster and uses fixed memory. - Ask about case and spaces. Clarify whether
Aandaare the same and whether spaces should be counted.
Recommended Approach: LinkedHashMap With merge()
Why: it runs in one pass, keeps the output order predictable and works for any character, not just letters. The merge() call keeps the code short without hiding what happens.