Hashmap implementation to count the occurrences of each character
import java.util.HashMap;
import java.util.Map;
...
Map<String, Integer> freq = new HashMap<String, Integer>();
...
int count = freq.containsKey(word) ? freq.get(word) : 0;
freq.put(word, count + 1);
Hai All The below code is to count the occurrence of each character and it should print the count. may be helps you..Thanks for seeing
package com.corejava;
import java.util.Map;
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
String str = "ramakoteswararao";
char[] char_array = str.toCharArray();
System.out.println("The Given String is : " + str);
Map<Character, Integer> charCounter = new TreeMap<Character, Integer>();
for (char i : char_array) {
charCounter.put(i,charCounter.get(i) == null ? 1 : charCounter.get(i) + 1);
}
for (Character key : charCounter.keySet()) {
System.out.println("occurrence of '" + key + "' is "+ charCounter.get(key));
}
}
}
Java 8 streams:
Map<String, Long> map =
Arrays.stream(string.split("")).
collect(Collectors.groupingBy(c -> c, Collectors.counting()));
Guava HashMultiset:
Multiset<Character> set = HashMultiset.create(Chars.asList("bbc".toCharArray()));
assertEquals(2, set.count('b'));
You're leaving char ch set as the same character through each execution of the loop.
It should be:
ch = char_array[i];
if(charCounter.containsKey(ch)){
charCounter.put(ch, charCounter.get(ch)+1);
}
else
{
charCounter.put(ch, 1);
}
Inside the for loop.