Java Program to find duplicate Characters in a String

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

Approach:

  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 = "java2blog.com ";
  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 :

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Comments

  1. How about using a Set?

    private static boolean hasDupeLetter(String str) {

    if(null == str || str.length() <= 1) { return false; } Set set = new HashSet();
    for(int i = 0; i < str.length(); i++) { set.add(str.charAt(i)); } return str.length() == set.size(); }

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.