Answer- Write a program to find repeated characters in a String. For example, if given input to your program is "Java", it should print all duplicates characters, i.e. characters appear more than once in String and their count e.g. a = 2 because character 'a' has appeared twice in String "Java".
The standard way to solve this problem is to get the character array from String, iterate through that and build a Map with character and their count. Then iterate through that Map and print characters which have appeared more than once. So you actually need two loops to do the job, the first loop to build the map and second loop to print characters and counts.
If you look at below example, there is only one static method called printDuplicateCharacters(), which does both this job. We first got the character array from String by calling toCharArray().
Next we are using HashMap to store characters and their count. We use containsKey() method to check if key, which is a character already exists or not, if already exists we get the old count from HashMap by calling get() method and store it back after incrementing it by 1.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
/* Java Program to find duplicate characters in String.
@author CSDT
*/
public class FindDuplicateCharacters
{
public static void main(String args[])
{
printDuplicateCharacters("Programming");
printDuplicateCharacters("Combination");
printDuplicateCharacters("Java");
}
/*
* Find all duplicate characters in a String and print each of them.
*/
public static void printDuplicateCharacters(String word)
{
char[] characters = word.toCharArray();
// build HashMap with character and number of times they appear in String
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
for (Character ch : characters)
{
if (charMap.containsKey(ch))
{
charMap.put(ch, charMap.get(ch) + 1);
}
else
{
charMap.put(ch, 1);
}
}
// Iterate through HashMap to print all duplicate characters of String
Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet();
System.out.printf("List of duplicate characters in String '%s' %n", word);
for (Map.Entry<Character, Integer> entry : entrySet)
{
if (entry.getValue() > 1)
{
System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());
}
}
}
}