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:
- HashMap based solution
- 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
- Java Program to Count Number of Duplicate Words in String
- Java Program to Count Number of Words in Given String
- Java Program to Count the Number of Occurrences of Substring in a String
- Java Program to Count the Occurrences of Each Character in String
- Java Program to Merge two String Arrays
- Java Program to Remove Duplicate Words from String
- Java Program to Reverse a String(5 ways)
- Java Program to Reverse Each Word of a String
- Java Program to Swap Two Strings
- How to Check if the String Contains only Digits
- How to Check if the String Contains only Letters
- How to Check If the String Contains Only Letters or Digits
- Java Program to Check if Input String is Palindrome
- Java Program to Find all Permutations of String
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment