Friday, December 27, 2024
Google search engine
HomeLanguagesJavaCount occurrence of a given character in a string using Stream API...

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 = "neveropen", 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 = "neveropen";
        char c = 'e';
        System.out.println(count(str, c));
    }
}


Output:

4

Related Article: Program to count occurrence of a given character in a string

RELATED ARTICLES

Most Popular

Recent Comments