Java Program to count words in a sentence using lambda expression
Java Lambda Program: Exercise-13 with Solution
Write a Java program to implement a lambda expression to count words in a sentence.
Sample Solution:
Java Code:
public class Main {
public static void main(String[] args) {
String text = "Java lambda expression.";
System.out.println("Original string: " + text);
WordCounter wordCounter = s -> s.split("\\s+").length;
int ctr = wordCounter.countWords(text);
System.out.println("Word count: " + ctr);
text = "The quick brown fox jumps over the lazy dog.";
System.out.println("\nOriginal string: " + text);
wordCounter = s -> s.split("\\s+").length;
ctr = wordCounter.countWords(text);
System.out.println("Word count: " + ctr);
}
}
@FunctionalInterface
interface WordCounter {
int countWords(String text);
}
Sample Output:
Original string: Java lambda expression. Word count: 3 Original string: The quick brown fox jumps over the lazy dog. Word count: 9
Explanation:
In the above code the wordCounter variable is assigned a lambda expression that splits the input string by whitespace (\\s+) and counts the number of resulting substrings using the length method. The countWords method of the wordCounter instance is then called with the text string. The result is stored in the "ctr" variable. Finally, the word count is printed to the console.
Flowchart:

Live Demo:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Java Lambda Exercises Previous: Multiply and sum elements with Lambda expression in Java.
Java Lambda Exercises Next: Java program to check Palindrome string using lambda expression.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How do I remove repeated elements from ArrayList?
If you don't want duplicates in a Collection, you should consider why you're using a Collection that allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList:
Set<String> set = new HashSet<>(yourList); yourList.clear(); yourList.addAll(set);
Of course, this destroys the ordering of the elements in the ArrayList.
Ref: https://bit.ly/3bYIjNC
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook