Pages

Counting the occurences of each character in a given string in java

In this example I will show you how to count the occurrences of each character in a given string.

For this we use HashMap. key for HashMap is the character and value is the number of occurrences.
public static void main(String[] args) {
  char[] ch = name.toLowerCase().toCharArray();
  HashMap<Character, Integer> map = new HashMap<>();

  for (int i = 0; i < ch.length; i++) {
   if (map.containsKey(ch[i])) {
    map.put(ch[i], map.get(ch[i]) + 1);
   }

   else {
    map.put(ch[i], 1);
   }
  }

  System.out.println(map);
 }
Output of the program 

{v=1,  =1, t=1, r=1, a=2, n=1, o=2, m=1, j=1, i=1}


How to write an immutable Class in Java

No comments:

Post a Comment