English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
To obtain the frequency of each string in a Java string, we will use Java's hash map collection. First, convert the string to a character array to easily access each character of the string.
Now, to compare if each character exists in the hash map (if it does not exist), simply add it to the hash map as a key and assign it a value; if the character exists, find its value which is the occurrence of this character in the string (when the character does not exist in the map, its initial value is set to1),then add one to it. Add this character and its updated count value to the map again.
In the final printout, the hash map will take each character as the key and its occurrence as the value.
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); } }
{a=2, r=1, s=2, d=3, f=1, h=2, i=1, k=1, l=1, o=1}