Java Program to Print all duplicate characters in a string?

There are following way to Print all duplicate characters in a string.

  • Create Hashmap object with character key and value in Integer type.
  • Convert the String in char using str.toCharArray() method.
  • Through for loop we iterate Char array,
  • Now store the value at depend on key inside map
  • From map.keySet() fetch the unique key parameter.
  • Again iterate the key and check if map.get(key)>1 means number of key value is more that 1.
  • Print the key as char and number in int value.
import java.util.HashMap;
import java.util.Set;

public class CountRepeatChar {
	public static void main(String[] args) {
		String str = "wellcome";
		HashMap<Character, Integer> map = new HashMap<Character, Integer>();
		char[] ch = str.toCharArray();
		for (char key : ch) {
			if (map.containsKey(key)) {
				map.put(key, map.get(key) + 1);
			} else {
				map.put(key, 1);
			}
		}
		Set<Character> st = map.keySet();
		for (Character cha : st) {
			if (map.get(cha) > 1) {
        System.out.println("character is :- " + cha + " ,Number of times :- " + map.get(cha));
			}
		}
	}
}

Output :-
character is :- e ,Number of times :- 2
character is :- l ,Number of times :- 2