In this short article, we will write a Java 8 program to counts the number of vowels and consonants in a given string.
We will use Java 8 lambda expression and stream API to write this program.
Java 8 program counts the number of vowels and consonants in a given string
package com.java.tutorials.programs;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author https://www.sourcecodeexamples.net/
*
*/
public class Java8Program {
private static final Set < Character > allVowels = new HashSet(Arrays.asList('a', 'e', 'i', 'o', 'u'));
public static void main(String[] args) {
String str = "sourcecodeexamples";
long vowels = str.chars()
.filter(c - > allVowels.contains((char) c))
.count();
long consonants = str.chars()
.filter(c - > !allVowels.contains((char) c))
.filter(ch - > (ch >= 'a' && ch <= 'z'))
.count();
System.out.println("vowels count => " + vowels);
System.out.println("consonants => " + consonants);
}
}
Output:
vowels count => 8
consonants => 10
Comments
Post a Comment