Count duplicate characters using Java 8



Write a Java 8 program (using Streams and Lambda) that counts duplicate characters from a given string.

Java 8 program to count duplicate characters

import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

public final class Strings {

    public static Map<Character, Long> countDuplicateCharacters(String str) {

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

        Map<Character, Long> result = str.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(c -> c, Collectors.counting()));

        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, Long> 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: 26707300 ns (26 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