Hi Guys.
Welcome to JAVA INSPIRES
In this post..we will see
How To Count Occurrences Of Each Character In a String In Java?
Give string ... "Google Apple Amazon Facebook Microsoft".
JavaBasicExample.java
package com.javainspires; import java.util.HashMap; /** * * @author Java Inspires * */ public class JavaBasicExample { // lets start public static void main(String[] args) { // lets take a string String inString = "Google Apple Amazon Facebook Microsoft"; // convert the string to char array char[] cArr = inString.toCharArray(); // create a hashmap - char as Key and Count as Value HashMap<Character, Integer> countMap = new HashMap<Character, Integer>(); // iterate over chararray for (char c : cArr) { // check for this char in count map if (countMap.containsKey(c)) { // get count and increment by 1 int newCount = countMap.get(c) + 1; // update new count in the map countMap.put(c, newCount); } else { // put this char in map with count as 1 countMap.put(c, 1); } } // now print the count map countMap.entrySet().stream().forEach(e -> { System.out.println(e.getKey() + "=" + e.getValue()); }); } }
=4 A=2 a=2 b=1 c=2 e=3 F=1 f=1 G=1 g=1 i=1 k=1 l=2 m=1 M=1 n=1 o=7 p=2 r=1 s=1 t=1 z=1
THANK YOU