Java Program to Count Duplicate Characters in a String



Write a program that counts duplicate characters from a given string.

Java Program to Count Duplicate Characters in a String

Java Program demonstrates the different ways to count duplicate characters in a String:
package com.company;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class JavaStreamExample {
    public static void main(String[] args) {
        Map<Character, Integer> duplicatesV1 = countDuplicateCharactersV1("I love Java programming language");
        System.out.println(Arrays.toString(duplicatesV1.entrySet().toArray()));
    }

    public static Map<Character, Integer> countDuplicateCharactersV1(String str) {

        if (str == null || str.isBlank()) {
            // or throw IllegalArgumentException
            return Collections.emptyMap();
        }

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

        // or use for(char ch: str.toCharArray()) { ... }
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            result.compute(ch, (k, v) -> (v == null) ? 1 : ++v);
        }

        return result;
    }
}

Output:

[ =4, a=5, e=2, g=4, i=1, I=1, J=1, l=2, m=2, n=2, o=2, p=1, r=2, u=1, v=2]

Comments