Write a Java program to get distinct characters and their count in a string.
Write a Java program to get distinct characters and their count in a string.
25422-Mar-2023
Home / DeveloperSection / Forums / Write a Java program to get distinct characters and their count in a string.
Aryan Kumar
28-Apr-2023Here's an example Java program that gets the distinct characters and their count in a string:
In this example, we first define a string called str that we want to count the distinct characters in. We then create a HashMap called charCountMap to store the count of each distinct character in the string.
Next, we iterate through each character in the string using a for loop. For each character, we check if it already exists in the charCountMap. If it does, we increment its count by 1. If it doesn't, we add the character to the map with a count of 1.
Finally, we print out the distinct characters and their count using a for-each loop to iterate over the entries in the charCountMap.
Krishnapriya Rajeev
24-Mar-2023The code given below finds all the distinct characters and their count in a string using Java: