Java Program to Count Duplicate Characters in a String

In this quick post, we will write a Java Program to Count Duplicate Characters in a String.
We will discuss two solutions to count duplicate characters in a String:
  1. HashMap based solution
  2. Java 8, functional-style solution

Java Program to Count Duplicate Characters in a String

package net.javaguides.corejava.programs;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class CountDuplicateCharacters {
 private static final String TEXT = "Be strong, be fearless, be beautiful. "
            + "And believe that anything is possible when you have the right "
            + "people there to support you.";
       
    public static void main(String[] args) {
        
        System.out.println("Input text: \n" + TEXT + "\n");
        
        System.out.println("HashMap based solution:");
        long startTimeV1 = System.nanoTime();
        
        Map<Character, Integer> duplicatesV1 = countDuplicateCharactersV1(TEXT);
        
        displayExecutionTime(System.nanoTime()-startTimeV1);
        System.out.println(Arrays.toString(duplicatesV1.entrySet().toArray()));
        // or: duplicatesV1.forEach( (k, v) -> System.out.print(k + "="+ v + ", "));
        
        System.out.println();        
        System.out.println("Java 8, functional-style solution:");
        long startTimeV2 = System.nanoTime();
        
        Map<Character, Long> duplicatesV2 = countDuplicateCharactersV2(TEXT);
        
        displayExecutionTime(System.nanoTime()-startTimeV2);
        System.out.println(Arrays.toString(duplicatesV2.entrySet().toArray()));
        // or: duplicatesV2.forEach( (k, v) -> System.out.print(k + "="+ v + ", "));
    }
    
    private static void displayExecutionTime(long time) {
        System.out.println("Execution time: " + time + " ns" + " (" +
                TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS) + " ms)");
    }
    
 // Note: For Unicode supplementary characters use codePointAt() instead of charAt()
    //       and codePoints() instead of chars()

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

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

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

        for (int i = 0; i < str.length(); i++) {
            
            char ch = str.charAt(i);

            Integer count = result.get(ch);
            if (count != null) {
                result.put(ch, ++count);
            } else {
                result.put(ch, 1);
            }
        }

        return result;
    }

    public static Map<Character, Long> countDuplicateCharactersV2(String str) {
        
        if (str == null) {
            // or throw IllegalArgumentException
            return Collections.EMPTY_MAP;
        }
     
        Map<Character, Long> result = str.chars()                
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(c -> c, Collectors.counting()));

        return result;
    }
}

Output

Input text: 
Java is a popular  general-purpose programming language and computing platform. It is fast, reliable, and secure.

HashMap based solution:
[ =16, a=13, b=1, c=2, d=2, e=8, f=2, g=6, i=5, I=1, J=1, l=6, ,=2, -=1, m=4, n=6, .=2, o=5, p=7, r=8, s=5, t=4, u=5, v=1]

Java 8, functional-style solution:
[ =16, a=13, b=1, c=2, d=2, e=8, f=2, g=6, I=1, i=5, J=1, ,=2, l=6, m=4, -=1, .=2, n=6, o=5, p=7, r=8, s=5, t=4, u=5, v=1]

Related Java Programs on String


Comments