
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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}
- Related Questions & Answers
- Find frequency of each word in a string in C#
- Find frequency of each word in a string in Python
- C program to find frequency of each digit in a string
- Python – Word Frequency in a String
- Write a java program to reverse each word in string?
- Write a java program to tOGGLE each word in string?
- Extracting each word from a string using Regex in Java
- Frequency of each character in String in Python
- Getting first letter of each word in a String using regex in Java
- Java Program to Capitalize the first character of each word in a String
- Write a Java program to capitalize each word in the string?
- Write a java program reverse tOGGLE each word in the string?
- How to print the first character of each word in a String in Java?
- Print first letter of each word in a string in C#
- Java Program to Find the Frequency of Character in a String
Advertisements