![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to count the occurrence of each character in a string using Hashmap
To count the occurrence of each character in a string using Hashmap, the Java code is as follows −
Example
import java.io.*; import java.util.*; public class Demo{ static void count_characters(String input_str){ HashMap<Character, Integer> my_map = new HashMap<Character, Integer>(); char[] str_array = input_str.toCharArray(); for (char c : str_array){ if (my_map.containsKey(c)){ my_map.put(c, my_map.get(c) + 1); }else{ my_map.put(c, 1); } } for (Map.Entry entry : my_map.entrySet()){ System.out.println(entry.getKey() + " " + entry.getValue()); } } public static void main(String[] args){ String my_str = "Joe Erien "; System.out.println("The occurence of every character in the string is "); count_characters(my_str); } }
Output
The occurence of every character in the string is 2 r 1 e 2 E 1 i 1 J 1 n 1 o 1
A class named Demo contains the function named ‘count_characters’. Here, a hashmap is created that will store the character and its count. This function iterates through the string and checks for the count of every character. In the main function, the string is defined, and the function is called on this string and relevant message is displayed on the console.
Advertisements