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.
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:
// Java program to count occurrences // of a character using Stream import java.util.stream.*; class GFG { // Method that returns the count of the given // character in the string public static long count(String s, char ch) { return s.chars() .filter(c -> c == ch) .count(); } // Driver method public static void main(String args[]) { String str = "geeksforgeeks"; char c = 'e'; System.out.println(count(str, c)); } } |
chevron_right
filter_none
Output:
4
Related Article: Program to count occurrence of a given character in a string
Recommended Posts:
- Program to count occurrence of a given character in a string
- Character Stream Vs Byte Stream in Java
- Minimize the length of string by removing occurrence of only one character
- Generate two output strings depending upon occurrence of character in input string.
- Generate two output strings depending upon occurrence of character in input string in Python
- Stream count() method in Java with examples
- Count of number of given string in 2D character array
- Count of strings that can be formed from another string using each character at-most once
- Count occurrences of a character in a repeated string
- Count occurrences of a given character using Regex in Java
- Java program to count the occurrences of each character
- Difference between Stream.of() and Arrays.stream() method in Java
- Find the first non-repeating character from a stream of characters
- Java Program to get a character from a String
- Queue based approach for first non-repeating character in a stream
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



