Find duplicate characters in a string java

 Posted On  | Yashwant Chavan 

In this tutorial we will learn how to find duplicate character and its occurrence count from input string.

You can refer my another article to count occurrence of each word. Both programs are base on same logic, in that I have used HashMap collection to store the char/string and its occurrence count in key value pair format respectively.

Find Duplicate Characters

package com.technicalkeeda.app;

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

public class FindDuplicateCharacters {

    public static void main(String[] args) {
        FindDuplicateCharacters findChars = new FindDuplicateCharacters();
        findChars.duplicateCharacters("Hello Yashwant");
        System.out.println("---------------------");
        findChars.duplicateCharacters("Nitin");
    }

    public void duplicateCharacters(String input) {

        Map < Character, Integer > data = new HashMap < Character, Integer > ();

        char[] charArray = input.toCharArray();

        for (Character c: charArray) {
            if (data.containsKey(c)) {
                data.put(c, data.get(c) + 1);
            } else {
                data.put(c, 1);
            }
        }

        for (Character c: data.keySet()) {
            if (data.get(c) > 1) {
                System.out.println("Char " + c + " occurs " + data.get(c) + " Times");
            }
        }
    }

}

Output

Char a occurs 2 Times
Char l occurs 2 Times
---------------------
Char i occurs 2 Times


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0325 seconds.