Find out each character in a word.
For Example: In Programming each character count is
p=1
a=1
r=2
g=2
i=1
m=2
n=1
o=1
Problem
Write a java code that will print each character and their count.
Code
import java.util.HashMap;
public class RepeatedCharacters {
public static void main(String[] args) {
String str1 = "programming";
char[] strArry = str1.toCharArray();
HashMap<Character, Integer> charMap = new HashMap<Character, Integer>();
for(Character ch: strArry) {
if (charMap.containsKey(ch)) {
charMap.put(ch, charMap.get(ch) + 1);
} else {
charMap.put(ch, 1);
}
}
System.out.println(charMap);
//iterate hashmap
charMap.forEach((k, v) -> System.out.println("Character : " + k + " Count : " + v));
}
}