Pages

Saturday, November 7, 2020

Java Program To Count Vowels and Consonants in a String

1. Introduction


In this article, We'll be learning how to find the total count of vowels and consonants in a string. The following shown examples are based on the English language. If you are targeting many languages, it will be based on the number of vowels and consonants in the selected language.

I hope, all of you are aware of the vowels and consonants in the English language. The total alphabets are 26. Among 5 are vowels and rest are considered as consonants.

Vowels: a, e, i, o, u
Consonants: Except vowels remaining all 21 will be categorized as consonants.





2. Java Program To Count Vowels and Consonants in a String


In the following program, mainly need to think about the lowercase and uppercase letters.

Steps :


A) Store all vowels into a List of characters.
B) Convert the string into either lowercase or uppercase. But, the string is getting into lowercase in the example.
C) Declare two count variables for each type such as countVowels and countCOnsonants.
D) Take each character from input string and check it is present in the list of vowels. If yes, increment variable countVowels by 1.
E) If it is not a vowel, then check that character is in between 'a' and 'z'. If yes, increment variable countCOnsonants by 1.
F) If it is not falling these two categories means that char is a special character such as #, %, $, etc.
H) Print the count values.

Let us take look at the complete program.

[package com.javaprogramto.w3schools.engineering.string;
import java.io.Console;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* Java Program To Count Vowels and Consonants in a String
*
* @version JavaProgramTo.com
*/
public class StringCountVowelsConsonants {
public static void main(String[] args) {
String input = "Welcome To The Java String Programming Article";
List<Character> vowels = new ArrayList<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
input = input.toLowerCase();
int countVowels = 0;
int countCOnsonants = 0;
for (int index = 0; index < input.length(); index++) {
char currentChar = input.charAt(index);
if (vowels.contains(currentChar)) {
countVowels++;
} else if (currentChar >= 'a' && currentChar <= 'z') {
countCOnsonants++;
}
}
System.out.println("Total count of vowels : "+countVowels);
System.out.println("Total count of consonants : "+countCOnsonants);
}
}]

Output:

Total count of vowels : 14
Total count of consonants : 26

Java Program To Count Vowels and Consonants in a String example

3. Java 8 Streams API


Let us write the same logic using chars() and filter() Stream API methods.

Read more on:

Java 8 Stream filter() examples
How to find the count of object with filter()
Differences between map() and filter()


package com.javaprogramto.w3schools.engineering.string;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.sun.tools.javac.util.Pair;

/**
 * 
 * Java Program To Count Vowels and Consonants in a String
 * 
 * @version JavaProgramTo.com
 */
public class StringCountVowelsConsonantsJava8 {

    public static void main(String[] args) {

        String input = "ANother input with special characters : ! @ # $ % ^ & * ( ) ";

        List<Character> vowels = new ArrayList<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
        input = input.toLowerCase();

        long countVowels = 0;
        long countCOnsonants = 0;

        countVowels = input.chars().filter(curretChar -> vowels.contains((char) curretChar)).count();

        countCOnsonants = input.chars().filter(curretChar -> !vowels.contains((char) curretChar))
                .filter(nonVowelCh -> (nonVowelCh >= 'a' && nonVowelCh <= 'z')).count();

        Pair<Long, Long> result = Pair.of(countVowels, countCOnsonants);

        System.out.println("Total count of vowels : " + countVowels);
        System.out.println("Total count of consonants : " + countCOnsonants);

        System.out.println("Pair object : " + result);
    }
}

Output:

Total count of vowels : 12
Total count of consonants : 21
Pair object : Pair[12,21]

This program is implemented by using an intermediate method filter() and terminal method count().
Once the terminal operation is in place only then the intermediate operations will be executed.

4. Java 8 Collectors.partitioningBy() and Collectors.counting() - Collectors API


Let us simplify the code further using Collectors API methods partitioningBy() and counting() methods.

package com.javaprogramto.w3schools.engineering.string;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 
 * Java 8 Streams Collectors API.
 * 
 * @version JavaProgramTo.com
 */
public class StringCountVowelsConsonantsJavaCollectors {

    public static void main(String[] args) {

        String input = "This is using Collectors api methods !!!!";

        List<Character> vowels = new ArrayList<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
        input = input.toLowerCase();

        IntStream stream = input.chars();

        Map<Boolean, Long> finalResultMap = stream.mapToObj(ch -> (char) ch).filter(ch -> (ch >= 'a' && ch <= 'z'))
                .collect(Collectors.partitioningBy(ch -> vowels.contains(ch), Collectors.counting()));

        System.out.println("Total count of vowels : " + finalResultMap.get(new Boolean(true)));
        System.out.println("Total count of consonants : " + finalResultMap.get(new Boolean(false)));

        System.out.println("finalResultMap map : " + finalResultMap);
    }
}

Output:

Total count of vowels : 11
Total count of consonants : 20
finalResultMap map : {false=20, true=11}

True means vowel, False means Consonants.

Java 8 Collectors.partitioningBy() and Collectors.counting() - Collectors API

5. Conclusion


In this article, We have seen the 3 ways to find the count of vowels and consonants in the given string. Always recommended is to go without java 8 concepts which give better performance.

Next example on how to get count of no of digits in a number?

Think about each solution before you use in your project the code.

No comments:

Post a Comment

Please do not add any spam links in the comments section.