Java count duplicate characters



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

Java program to count duplicate characters

import java.util.Collections;

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

public final class Strings {

    public static Map<Character, Integer> countDuplicateCharacters(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;
    }
}

Test Java program to count duplicate characters

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class Main {

    private static final String TEXT = " Java is my fav programming language. I love Java coding";
    
    public static void main(String[] args) {
        
        
        System.out.println("HashMap based solution:");
        long startTimeV1 = System.nanoTime();
        
        Map<Character, Integer> duplicatesV1 = Strings.countDuplicateCharacters(TEXT);
        
        displayExecutionTime(System.nanoTime()-startTimeV1);
        System.out.println(Arrays.toString(duplicatesV1.entrySet().toArray()));
    }
    
    private static void displayExecutionTime(long time) {
        System.out.println("Execution time: " + time + " ns" + " (" +
                TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS) + " ms)");
    }

}

Output:

HashMap based solution:
Execution time: 14567100 ns (14 ms)
[ =10, a=8, c=1, d=1, e=2, f=1, g=5, I=1, i=3, J=2, l=2, m=3, .=1, n=3, o=3, p=1, r=2, s=1, u=1, v=4, y=1]

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments