Java Program to Count Individual Vowels in a String / Line Example with TreeMap

Write a program to count Individual Vowels in a String / Line using TreeMap. This program may be asked in core java  written exam. The following program counts the total number of Vowels in a String or Line. Also counts the number of individual vowels. For this we will use TreeMap to count individual vowels. Please go through below java program that uses Treemap that does not allow duplicates. Individual vowels are stored as a key in treemap. Individual vowels count is stored as a value in the treemap by checking the vowel is already in the map. if it is already in the map, the count is increased and stored as a value. charAt() method is used to get each character in the String.

package net.javaonline;

import java.lang.String;
import java.io.*;
import java.util.*;

public class VowelsCount {
	public static void main(String args[]) throws IOException {
		String str = "";
		Scanner in = new Scanner(System.in);
		System.out.println("Enter any  String: ");
		str = in.nextLine();
		int totalVowels = 0;
		Map<Character, Integer> tmap = new TreeMap<Character, Integer>();
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (c == 'A' || c == 'a' || c == 'E' || c == 'e' || c == 'I'
					|| c == 'i' || c == 'O' || c == 'o' || c == 'U' || c == 'u') {
				Integer count = tmap.get(c);
				tmap.put(c, (count == null ? 1 : count + 1));
				totalVowels++;
			}
		}
		System.out.println("Total Number of Vowels in the String  "
				+ totalVowels);
		System.out.println(tmap);
	}
}

Output :

Vowels Count

You may also like

Leave a Reply

Be the First to Comment!