Program to find Repeated/Duplicate Characters of String

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

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());
}
}
}
}

List of duplicate characters in String 'Programming'
r : 2
g : 2
m : 2
List of duplicate characters in String 'Combination'
i : 2
n : 2
o : 2
List of duplicate characters in String 'Java'
a : 2

Comments

Popular posts from this blog

Android - Using KeyStore to encrypt and decrypt the data

Stack and Queue

Java Reflection API