this is an frequently asked questions and problem in solving String .

This post covers an problems related to repeated character in String.

  • Find Each Character Count of a string using HashMap

  • Find duplicate characters in a String and count the number of occurrences using Java

  • Character Count display with hashmap in java

This program does following things input: ‘abbc’ and output:

a - 1
b - 2
c - 1
import java.util.HashMap;

public class Test1 {
    public static void main(String[] args) {
        String str = "helllo";
        printCharacterCount(str);
    }
    public static void printCharacterCount(String str) {
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < str.length(); i++) {
            Character character = str.charAt(i);
            if (map.containsKey(character)) {
                Integer value = map.get(character);
                map.put(character, ++value);
            }
            else{
                map.put(character, 1);

            }
        }
        map.entrySet().stream().forEach(e-> System.out.println(e));

    }

Output:

a=1
b=2
c=1

Find Most repeated character count and character in a string

package com;

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

public class Test1 {
    public static void main(String[] args) {
        String str = "helllo";
        findRepeatedCharacterCount(str);
    }

    public static void findRepeatedCharacterCount(String str) {
        Character repeatedChar = 1;
        Integer maxCount = 0;
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < str.length(); i++) {
            Character character = str.charAt(i);
            if (map.containsKey(character)) {

                Integer value = map.get(character);
                map.put(character, ++value);
                if (maxCount < value) {
                    repeatedChar = character;
                    maxCount = 1 + value;
                }

            } else {
                map.put(character, 1);
                if (maxCount < 1) {
                    repeatedChar = character;
                    maxCount = 1;
                }

            }

        }
        System.out.println("Most Frequent Repeated Character: " + repeatedChar);
        System.out.println("Most Frequent Repeated Character Count: " + maxCount);

    }
}

Output:

Most Frequent Repeated Character: l
Most Frequent Repeated Character Count: 3