Java Program to Find Duplicate Character from a String and Count of repetition

Java Program to Find Duplicate Character from a String and Count of repetition thumbnail
11K
By Dhiraj ray 31 December, 2017

Description

While dealing with string, many of the time it is required to find or remove duplicate character from a string.Following is the java program to find duplicate or repeated characters from a given string.The program also results the cont of the duplicate characters.

package com.devglan;

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

public class DuplicateChar {

    public void findDuplicateCharsInString(String str){

        Map map = new HashMap();
        char[] chars = str.toCharArray();
        for(Character ch : chars){
            if(map.containsKey(ch)){
                map.put(ch, map.get(ch)+1);
            } else {
                map.put(ch, 1);
            }
        }
        Set keys = map.keySet();
        for(Character ch : keys){
            if(map.get(ch) > 1){
                System.out.println(ch + " -- " + map.get(ch));
            }
        }
    }

    public static void main(String a[]){
        DuplicateChar duplicateChar = new DuplicateChar();
        duplicateChar.findDuplicateCharsInString("india");
    }
}

Explanation

As we know, HashMap implementation in java holds key value pair and it does not provide duplicate keys, here in the program we have used hashmap to hold the different character of a string and whenver a key already exists in the map simply increase the count of the hashmap value.At the end we can get the duplicate character whose hashmap value is greater then 1 along with the repeated count of the character.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.