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.
Examples:
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.
Approach:
- 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:
import java.util.stream.*;
class GFG {
public static long count(String s, char ch)
{
return s.chars()
.filter(c -> c == ch)
.count();
}
public static void main(String args[])
{
String str = "geeksforgeeks" ;
char c = 'e' ;
System.out.println(count(str, c));
}
}
|
Related Article: Program to count occurrence of a given character in a string
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
29 May, 2019
Like Article
Save Article