Given a string and a character, the task is to create a function that uses the Stream API to detect occurrences of certain characters in the string.
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:
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)); } }
Output:
4
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.