Learn how to count specific characters in a string in Java using toCharArray(), for loop, and Java 8 Stream API . In this example, we count the occurrences of the character ‘h’ in each string.
Code Explanation point wise
- Now the cd.test(‘h’, str) method passes the character ‘h’ and the string str as arguments.
- The test(char c, String str) method counts the occurrences of ‘h’ in the string and returns the count.
- After stores the returned count in the variable i.
- Prints the total number of occurrences of ‘h’ using the toCharArray() method and a for loop.
- The str.chars() method converts the string into an IntStream of character Unicode values.
- Now .mapToObj(x -> (char) x) method converts each integer value into a Character object.
- After .filter(ch -> ch == ‘h’) checks each character in the stream.
- Keeps only the characters that are equal to ‘h’.
- .count() counts all matching characters in the stream.
- Returns the total number of occurrences of ‘h’.
- Prints the count obtained using the Java 8 Stream API.
public class CountCharDemo {
public static void main(String[] args) {
CountCharDemo cd = new CountCharDemo();
String str = "how are you well here";
// Using toCharArray() and for loop
int i = cd.test('h', str);
System.out.println("Total number of characters from toCharArray(): " + i);
// Using Java 8 Stream API
long count = str.chars()
.mapToObj(x -> (char) x)
.filter(ch -> ch == 'h')
.count();
System.out.println("From Java 8 map and filter: " + count);
}
public int test(char c, String str) {
int count = 0;
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (c == ch[i]) {
count++;
}
}
return count;
}
}
Output :-
total number of character from TocharArray :- 2
from java8 map and filter :- 2
Count Character Frequency in a String in Java Using Java 8 Streams
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CharacterFrequency {
public static void main(String[] args) {
String str = "how are you well here";
Map frequencyMap = str.chars()
.mapToObj(ch -> (char) ch)
.filter(ch -> ch != ' ')
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()));
frequencyMap.forEach((key, value) ->
System.out.println(key + " = " + value));
}
}
Output :
h = 2
o = 2
w = 2
a = 1
r = 2
e = 4
y = 1
u = 1
l = 2
Here are some related Java 8 programs that will help you understand Stream API concepts better:
FAQ
How do you count a specific character in a string in Java?
You can count a character using a for loop, toCharArray(), or Java 8 Stream API methods such as filter() and count().
What does toCharArray() do in Java?
The toCharArray() method converts a string into a character array.
How can Java 8 Streams count characters?
Java 8 Streams use chars(), filter(), and count() to count matching characters efficiently.
What is the time complexity of counting characters in a string?
The time complexity is O(n) because each character is visited once.