Java Program to find duplicate Characters in a String

In this post, we will see how to find duplicate Characters in a String.


  1. Create a HashMap and character of String will be inserted as key and its count as value.
  2. If Hashamap already contains char,increase its count by 1, else put char in HashMap
  3. If value of Char is more than 1, that means it is duplicate character in that String

Java Program to find duplicate Characters in a String

package org.arpit.java2blog;

import java.util.HashMap;
import java.util.Set;

public class StringFindDuplicatesMain {

 public static void main(String[] args) {
  String str = " ";
  HashMap charCountMap = new HashMap();
  for (int i = 0; i < str.length(); i++) {
   char c = str.charAt(i);

   if (charCountMap.containsKey(c)) {
    charCountMap.put(c, charCountMap.get(c) + 1);
   } else {
    charCountMap.put(c, 1);

  for (Character c : charCountMap.keySet()) {
   if (charCountMap.get(c) > 1)
    System.out.println("duplicate character : " + c + " ====== " + " count : " + charCountMap.get(c));




When you run above program, you will get below output:
duplicate character : a ======  count : 2
duplicate character : o ======  count : 2

Other String Programs :

    How to reverse String in java How to check if two Strings are angrams Find length of String without using java inbuilt length method Find all substrings of String in java Find First non repeated character in a String Java Program to check Palindrome String Why String is immutable in java Find duplicate characters in String

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012