w3resource

Java Program: Count Strings Starting with Specific Letter using Streams

Java Stream: Exercise-5 with Solution

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:

Flowchart: Java Stream  Exercises - Remove Duplicate Elements from List 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.



Follow us on Facebook and Twitter for latest update.