Java 8 Program to Count Duplicate Characters in a String - Lambda Expression



In this quick post, we will write a Java 8 Program to Count Duplicate Characters in a String.

We use Java 8, a functional-style solution to write this Java program.

Java 8 Program 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;
import java.util.stream.Collectors;

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

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

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