Java Program to Count Occurrences of Each Character in a String
- Using HashMap
- Using Java 8 Streams
Java Program to Count Occurrences of Each Character in a String using HashMap
In this method, we will use a HashMap to count the occurrences of each character in a given string. We will iterate over each character in the string and store the count of each character in the HashMap. Finally, we will print the count of each character in the string. We will follow the below steps to count the occurrences of each character in a string using HashMap:
- Create a HashMap to store the count of each character in the string.
- Iterate over each character in the string.
- Check if the character is present in the HashMap.
- If the character is present, increment the count by 1.
- If the character is not present, add the character to the HashMap with count 1.
- Finally, print the count of each character in the string.
import java.util.HashMap;
import java.util.Map;
public class CountCharacters {
public static void main(String[] args) {
String str = "Hello, World!";
Map charCountMap = new HashMap<>();
for (char ch : str.toCharArray()) {
if (Character.isLetter(ch)) {
charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
}
}
for (Map.Entry entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
H : 1
e : 1
l : 3
o : 2
W : 1
r : 1
d : 1
Time Complexity: O(n) - where n is the length of the string as we are iterating over each character in the string.
Space Complexity: O(n) - where n is the length of the string as we are storing the count of each character in the HashMap.
Java Program to Count Occurrences of Each Character in a String using Java 8 Streams
In this method, we will use Java 8 Streams to count the occurrences of each character in a given string. We will convert the string to a character stream and group the characters by counting the occurrences of each character. Finally, we will print the count of each character in the string. We will follow the below steps to count the occurrences of each character in a string using Java 8 Streams:
- Convert the string to a character stream.
- Group the characters by counting the occurrences of each character.
- Finally, print the count of each character in the string.
import java.util.Map;
import java.util.stream.Collectors;
public class CountCharacters {
public static void main(String[] args) {
String str = "Hello, World!";
Map charCountMap = str.chars()
.mapToObj(c -> (char) c)
.filter(Character::isLetter)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
charCountMap.forEach((k, v) -> System.out.println(k + " : " + v));
}
}
H : 1
e : 1
l : 3
o : 2
W : 1
r : 1
d : 1
Time Complexity: O(n) - where n is the length of the string as we are iterating over each character in the string.
Space Complexity: O(n) - where n is the length of the string as we are storing the count of each character in the Map.
- Recommended Links
- Selenium Interview Questions