$show=/label

Java Program To Count Vowels and Consonants in a String

SHARE:

A quick java programming guide to find the count of vowels and consonants in a given string. Bonus Java 8 solution with Stream + Collectors API.

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.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Program To Count Vowels and Consonants in a String
Java Program To Count Vowels and Consonants in a String
A quick java programming guide to find the count of vowels and consonants in a given string. Bonus Java 8 solution with Stream + Collectors API.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7P3fZZiyPUxvMFruYcxUtH_VpWxpLQREJ_pIFbEESYBMGU0D1hQkOx2GM7HruVc2KLtVgnTWOxhpKK3o3DVxKas2gFnpaXLaYD-BcRfwDpPEecvOnsBXBd7Ec3WgYXFbvHoW9jVGADbg/s640/Java+Program+To+Count+Vowels+and+Consonants+in+a+String.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7P3fZZiyPUxvMFruYcxUtH_VpWxpLQREJ_pIFbEESYBMGU0D1hQkOx2GM7HruVc2KLtVgnTWOxhpKK3o3DVxKas2gFnpaXLaYD-BcRfwDpPEecvOnsBXBd7Ec3WgYXFbvHoW9jVGADbg/s72-c/Java+Program+To+Count+Vowels+and+Consonants+in+a+String.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/03/java-program-count-vowels-consonants.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/03/java-program-count-vowels-consonants.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content