Java Program: Count Strings Starting with Specific Letter using Streams
Write a Java program to count the number of strings in a list that start with a specific letter using streams.
Sample Solution:
Java Code:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List < String > colors = Arrays.asList("Red", "Green", "Blue", "Pink", "Brown");
System.out.println("Original list of strings (colors): " + colors);
char startingLetter = 'B';
// Count strings starting with a specific letter
long ctr = colors.stream()
.filter(s -> s.startsWith(String.valueOf(startingLetter)))
.count();
System.out.println("\nNumber of colors starting with '" + startingLetter + "': " + ctr);
char startingLetter1 = 'Y';
// Count strings starting with a specific letter
ctr = colors.stream()
.filter(s -> s.startsWith(String.valueOf(startingLetter1)))
.count();
System.out.println("\nNumber of colors starting with '" + startingLetter1 + "': " + ctr);
}
}
Sample Output:
Original list of strings (colors): [Red, Green, Blue, Pink, Brown] Number of colors starting with 'B': 2 Number of colors starting with 'Y': 0
Explanation:
In the above exercise, we have a list of strings ("Red", "Green", "Blue", "Pink", "Brown"). We want to count the number of strings that start with a specific letter, which is defined by the startingLetter variable (in this case, 'a').
Using streams, we call the filter() method to filter out only strings that start with the specified letter. Then, we use the count() method to get the count of those filtered strings. Finally, the original list and the count of strings starting with the specific letter are printed to the console.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Java program to count the number of strings in a list that start with any vowel using streams.
- Write a Java program to count strings that start with a user-specified prefix using streams.
- Write a Java program to filter and count the number of strings that start with an uppercase letter using streams.
- Write a Java program to count strings that start with a specific letter and have a minimum length, using streams.
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Remove Duplicate Elements from List using Streams.
Next: Sort List of Strings in Ascending and Descending Order using Streams.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics