Java Program to Count Number of Repeated Characters in a String

In this post, we will different ways to count duplicate or repeated characters from a given String in Java.

Using a HashMap

The HashMap approach utilizes a key-value data structure to store characters as keys and their respective occurrence counts as values.

Example:
import java.util.HashMap;
import java.util.Map;

public class CountDuplicateCharacters {
    public static void main(String[] args) {
        String str = "programming";
        Map<Character, Integer> charCountMap = new HashMap<>();

        for (char c : str.toCharArray()) {
            charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
        }

        // Display duplicate characters along with their counts
        System.out.println("Duplicate Characters:");
        for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }
        }
    }
}

Output:

Duplicate Characters:
g: 2
r: 2
m: 2

Using an Array

This method uses an array to keep track of the occurrences of each character in the string. It is suitable when dealing with strings containing only ASCII characters. 

Example:
public class CountDuplicateCharacters {
    public static void main(String[] args) {
        String str = "programming";
        int[] charCount = new int[256];

        for (char c : str.toCharArray()) {
            charCount[c]++;
        }

        // Display duplicate characters along with their counts
        System.out.println("Duplicate Characters:");
        for (int i = 0; i < charCount.length; i++) {
            if (charCount[i] > 1) {
                System.out.println((char) i + ": " + charCount[i]);
            }
        }
    }
}

Output:

Duplicate Characters:
g: 2
r: 2
m: 2

Using Java 8 Streams

With Java 8, you can utilize Streams to count the duplicate characters in the string.

Example:
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CountDuplicateCharacters {
    public static void main(String[] args) {
        String str = "programming";
        Map<Character, Long> charCountMap = str.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        // Display duplicate characters along with their counts
        System.out.println("Duplicate Characters:");
        charCountMap.entrySet().stream()
                .filter(entry -> entry.getValue() > 1)
                .forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue()));
    }
}

Output:

Duplicate Characters:
g: 2
r: 2
m: 2

Conclusion

Counting duplicate or repeated characters in a string is a fundamental operation in Java. We have demonstrated three different methods to achieve this goal. Depending on your use case and preference, you can choose the HashMap approach for flexibility, the Array approach for efficiency with ASCII characters, or the Java 8 Streams approach for concise code. These methods provide you with the ability to efficiently handle strings and extract valuable information for further processing in your Java applications.

Comments