Write a Java program using Lambda Expression to find the number of words that start with a vowel in a list of strings


The java program that counts the number of words starting with a vowel in a list of strings using Java Streams and regular expressions. Here's an explanation of the code:

  • An ArrayList named fruits is created to store a list of strings.
  • The fruits list is populated with various fruit names, some of which start with vowels and some do not.
  • System.out.println("Given Words : " + fruits); prints the original list of words.
  • The program uses Java Streams to filter and count the words starting with a vowel:
    • fruits.stream(): This converts the fruits list into a stream of strings.
    • .filter(s -> s.matches("(?i)[aeiou].*")): This is a filter operation that retains only the words in the stream that match the regular expression pattern (?i)[aeiou].*. The pattern (?i) makes the regular expression case-insensitive, and [aeiou] matches any character that is a vowel. .* matches the rest of the characters in the word.
    • .count(): This counts the number of words in the stream that match the filter criteria.
  • System.out.println("Number of Words Starting with a Vowel : " + count); prints the count of words starting with a vowel.

Source Code

import java.util.ArrayList;
import java.util.List;
 
public class WordsStartingWithVowel
{
	public static void main(String[] args)
	{
		List<String> fruits = new ArrayList<>();
		fruits.add("apple");
		fruits.add("banana");
		fruits.add("cherry");
		fruits.add("oranges");
		fruits.add("date");
 
		System.out.println("Given Words : " + fruits);
 
		long count = fruits.stream().filter(s -> s.matches("(?i)[aeiou].*")).count();
 
		System.out.println("Number of Words Starting with a Vowel : " + count);
	}
}

Output

Given Words : [apple, banana, cherry, oranges, date]
Number of Words Starting with a Vowel : 2

Example Programs