How to find duplicate Characters in a String in Java Program ?

  Java Interview Q&A

Dear readers, today we create a program which is find duplicate characters in a String and would display the count of them.

Java Program to find duplicate Characters in a String using HashMap

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
public class Details {
 
  public void countDupChars(String str){
 
    //Create a HashMap 
    Map<Character, Integer> map = new HashMap<Character, Integer>(); 
 
    //Convert the String to char array
    char[] chars = str.toCharArray();
 
    /* logic: char are inserted as keys and their count
     * as values. If map contains the char already then
     * increase the value by 1
     */
    for(Character ch:chars){
      if(map.containsKey(ch)){
         map.put(ch, map.get(ch)+1);
      } else {
         map.put(ch, 1);
        }
    }
 
    //Obtaining set of keys
    Set<Character> keys = map.keySet();
 
    /* Display count of chars if it is
     * greater than 1. All duplicate chars would be 
     * having value greater than 1.
     */
    for(Character ch:keys){
      if(map.get(ch) > 1){
        System.out.println("Char "+ch+" "+map.get(ch));
      }
    }
  }
 
  public static void main(String a[]){
    Details obj = new Details();
    System.out.println("String: fastread.in");
    System.out.println("-------------------------");
    obj.countDupChars("fastread.in");
  
    System.out.println("\nString: Manishadubey");
    System.out.println("-------------------------");
    obj.countDupChars("Manishadubey");
 
    System.out.println("\nString: #@$@!#$%!!%@");
    System.out.println("-------------------------");
    obj.countDupChars("#@$@!#$%!!%@");
  }
}

Output:

String: fastread.in
-------------------------
Char e 1
Char t 1
Char a 2
Char s 1

String: Manishadubey
-------------------------
Char a 2
Char s 1
Char h 1
Char e 1

String: #@$@!#$%!!%@
-------------------------
Char # 2
Char ! 3
Char @ 3
Char $ 2
Char % 2

Read here complete . JAVA Program Tutorial

LEAVE A COMMENT