Introduction
Counting the number of vowels and consonants in a string is a common task in text processing and analysis. Whether you’re working on natural language processing, text analytics, or just a simple string manipulation task, identifying and counting vowels and consonants is a fundamental operation. Java 8 provides a streamlined way to perform this task using the Stream API. In this guide, we will explore how to create a Java program that counts the number of vowels and consonants in a string.
Problem Statement
The task is to create a Java program that:
- Accepts a string as input.
- Uses Java 8 Streams to count the number of vowels and consonants.
- Outputs the counts of vowels and consonants separately.
Example 1:
- Input:
"Hello World" - Output:
Vowels: 3, Consonants: 7
Example 2:
- Input:
"Java Programming" - Output:
Vowels: 5, Consonants: 9
Solution Steps
- Input String: Start with a string that can either be hardcoded or provided by the user.
- Define Vowels: Create a set of characters representing the vowels (both lowercase and uppercase).
- Stream Processing: Convert the string into a stream of characters, filter vowels and consonants, and count them.
- Display the Result: Print the number of vowels and consonants.
Java Program
Java 8 Program to Count Vowels and Consonants in a String
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Java 8 Program to Count Vowels and Consonants in a String
* Author: https://www.rameshfadatare.com/
*/
public class VowelsAndConsonantsCount {
public static void main(String[] args) {
// Step 1: Take input string
String input = "Hello World";
// Step 2: Count vowels and consonants using streams
VowelConsonantCounts counts = countVowelsAndConsonants(input);
// Step 3: Display the result
System.out.println("Vowels: " + counts.getVowelCount());
System.out.println("Consonants: " + counts.getConsonantCount());
}
// Method to count vowels and consonants in a string
public static VowelConsonantCounts countVowelsAndConsonants(String input) {
// Define vowels
Set<Character> vowels = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
// Filter and count vowels
long vowelCount = input.chars()
.mapToObj(c -> (char) c)
.filter(vowels::contains)
.count();
// Filter and count consonants
long consonantCount = input.chars()
.mapToObj(c -> (char) c)
.filter(c -> Character.isLetter(c) && !vowels.contains(c))
.count();
return new VowelConsonantCounts(vowelCount, consonantCount);
}
}
// Class to hold vowel and consonant counts
class VowelConsonantCounts {
private final long vowelCount;
private final long consonantCount;
public VowelConsonantCounts(long vowelCount, long consonantCount) {
this.vowelCount = vowelCount;
this.consonantCount = consonantCount;
}
public long getVowelCount() {
return vowelCount;
}
public long getConsonantCount() {
return consonantCount;
}
}
Explanation of the Program
-
Input Handling: The program uses the string
"Hello World"as an example input. This can be modified to accept input from the user if required. -
Defining Vowels: A
Setof characters is used to store both lowercase and uppercase vowels (a, e, i, o, u, A, E, I, O, U). -
Counting Vowels: The
chars()method converts the input string into anIntStreamof character codes. These are then converted into a stream ofCharacterobjects usingmapToObj. Thefilter()method counts how many of these characters are vowels by checking if they exist in thevowelsset. -
Counting Consonants: Another stream is used to count consonants. This stream filters out any characters that are not letters or are vowels, ensuring that only consonants are counted.
-
Result Storage: The counts for vowels and consonants are stored in a custom class,
VowelConsonantCounts, which makes it easy to handle and display the results. -
Output: The program prints the number of vowels and consonants in the input string.
Output Example
Example 1:
Input: Hello World
Output:
Vowels: 3
Consonants: 7
Example 2:
Input: Java Programming
Output:
Vowels: 5
Consonants: 9
Advanced Considerations
-
Case Sensitivity: The program handles both lowercase and uppercase vowels by including both in the
Set. This ensures that the counts are case-insensitive. -
Handling Non-Letter Characters: The program counts only letters as consonants, ignoring spaces, punctuation, and numbers. This ensures that the counts reflect only alphabetic characters.
-
Performance Considerations: This approach is efficient for typical string lengths and leverages the functional programming features of Java 8. The use of streams provides a clear and concise method for counting vowels and consonants.
Conclusion
This Java 8 program efficiently counts the number of vowels and consonants in a string using streams. By taking advantage of the Stream API, the solution is both concise and powerful, making it suitable for various text processing tasks. Whether you’re analyzing text, developing language processing tools, or just working on string manipulation, this method provides an effective approach to counting vowels and consonants in any given string.