Find frequency of each word in a string in Java


In order to get frequency of each in a string in Java we will take help of hash map collection of Java.First convert string to a character array so that it become easy to access each character of string.

Now compare for each character that whether it is present in hash map or not in case it is not present than simply add it to hash map as key and assign one as its value.And if character is present than find its value which is count of occurrence of this character in the string (initial we put as 1 when it is not present in map) and add one to it.Again put the this character into the map with the updated value of its count.

In last print the hash map which will give the each character as key and its occurrence as value.

Example

 Live Demo

import java.util.HashMap;
public class FrequencyOfEachWord {
   public static void main(String[] args) {
      String str = "aaddrfshdsklhio";
      char[] arr = str.toCharArray();
      HashMap<Character,Integer> hMap = new HashMap<>();
      for(int i= 0 ; i< arr.length ; i++) {
         if(hMap.containsKey(arr[i])) {
            int count = hMap.get(arr[i]);
            hMap.put(arr[i],count+1);
         } else {
            hMap.put(arr[i],1);
         }
      }
      System.out.println(hMap);
   }
}

Output

{a=2, r=1, s=2, d=3, f=1, h=2, i=1, k=1, l=1, o=1}

Updated on: 26-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements