Write a Java program using Lambda Expression to count the number of words in a given sentence (words are separated by spaces)


The java program that counts the number of words in a given sentence using a lambda expression and a custom functional interface WordCounter. Here's an explanation of the code:

  • The CountNoWords class is defined, which contains the main method.
  • Inside the main method:
    • WordCounter wordCounter = sentence -> sentence.split("\\s+").length;: This line creates a lambda expression that counts the number of words in a sentence. It uses the split("\\s+") method to split the sentence into words based on spaces and then counts the number of resulting words.
    • System.out.println("Number of Words : " + wordCounter.countWords("Welcome Tutor Joes Computer Education"));: This line uses the wordCounter lambda expression to count the number of words in the given sentence and prints the result.
  • The WordCounter functional interface is defined, which declares a single method named countWords that takes a sentence (as a string) and returns an integer representing the number of words in the sentence.

Source Code

public class CountNoWords
{
	public static void main(String[] args)
	{
		WordCounter wordCounter = sentence -> sentence.split("\\s+").length;
		System.out.println("Number of Words : "+wordCounter.countWords("Welcome Tutor Joes Computer Education"));
	}
}
interface WordCounter
{
	int countWords(String sentence);
}

Output

Number of Words : 5

Example Programs