How to find the count of each character in a String in Java

In this blog post, I will be demonstrating how you can determine the number of occurrences of each character in a String. Consider the following code snippet:

package learnjava.strings;import java.util.HashMap;import java.util.Map;public class CountCharactersDemo {public static void main(String[] args) {String str = "Hello World";Map<Character,Integer> characterCountMap = new HashMap<Character,Integer>(); //map stores each character and its countchar[] charsInStr = str.toCharArray();for(char c:charsInStr){if(characterCountMap.containsKey(c)){ //if the character is already in the map, just increment its countint count = characterCountMap.get(c);count++;characterCountMap.put(c, count);}else{ //if the character is not in the map, add it to the mapcharacterCountMap.put(c, 1);}}for(Character c:characterCountMap.keySet()){System.out.println("Character "+c+" occurs "+characterCountMap.get(c));}}}

 

The characterCountMap defines a HashMap that stores each character as a key and its count as a value. A for loop then iterates through the characters in the input String. It checks if the character is already in the map. If so, it just increments the count. If the character is not in the map, it adds it to the Map. So when you run this program, you will get the following output:

Character occurs 1Character r occurs 1Character d occurs 1Character e occurs 1Character W occurs 1Character H occurs 1Character l occurs 3Character o occurs 2

Comments

Popular posts from this blog

How to use logging in SpringBoot with code samples

Python While Loop with code samples

How to convert a List to a Set