Count occurrence of a given character in a string using Stream API in Java
Given a string and a character, the task is to make a function which counts the occurrence of the given character in the string using Stream API.
Input: str = "geeksforgeeks", c = 'e' Output: 4 'e' appears four times in str. Input: str = "abccdefgaa", c = 'a' Output: 3 'a' appears three times in str.
- Convert the string into character stream
- Check if the character in the stream is the character to be counted using filter() function.
- Count the matched characters using the count() function
Below is the implementation of the above approach:
Related Article: Program to count occurrence of a given character in a string
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.