Java Online Compiler
Example: Count Vowels and Consonants - Java 8 Streams in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Count Vowels and Consonants - Java 8 Streams import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize Scanner and get input string Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String inputString = scanner.nextLine(); scanner.close(); // Step 2: Convert the string to lowercase for easier comparison String lowerCaseString = inputString.toLowerCase(); // Step 3: Define a string of vowels for quick lookup String vowels = "aeiou"; // Step 4: Count vowels using streams long vowelCount = lowerCaseString.chars() // Get an IntStream of character codes .filter(c -> Character.isLetter(c)) // Filter for alphabetic characters .filter(c -> vowels.indexOf(c) != -1) // Filter for characters present in 'vowels' string .count(); // Count the remaining characters // Step 5: Count consonants using streams long consonantCount = lowerCaseString.chars() // Get an IntStream of character codes .filter(c -> Character.isLetter(c)) // Filter for alphabetic characters .filter(c -> vowels.indexOf(c) == -1) // Filter for characters NOT present in 'vowels' string .count(); // Count the remaining characters // Step 6: Print the results System.out.println("Vowels: " + vowelCount); System.out.println("Consonants: " + consonantCount); } }
Output
Clear
ADVERTISEMENTS