Wednesday, January 5, 2022

Find Duplicate Characters in a String With Repetition Count Java Program

In this post we’ll see a Java program to find duplicate characters in a String along with repetition count of the duplicates.

Finding duplicates characters in a String and the repetition count program is easy to write using a HashMap but you may be asked to write it without using any Java collection. Java 8 onward, you can also write this logic using Java Stream API. In this post we’ll see all of these solutions.


Java program to find duplicate characters in a String without using any library

If you are not using HashMap then you can iterate the passed String in an outer and inner loop and check if the characters are equal or not. If equal, then increment the count. In case characters are equal you also need to remove that character from the String so that it is not counted again in further iterations.

public class DuplicateChars {

  public static void main(String[] args) {   
    findDuplicateCharsWithCount("kakatua parrot is a bird");
    System.out.println("------------");
    findDuplicateCharsWithCount("John was jealous");
    System.out.println("------------");
    findDuplicateCharsWithCount("rats");
  }
    
  private static void findDuplicateCharsWithCount(String str) {
    System.out.println("Duplicates in- "+ str);
    int count;
    for(int i = 0; i < str.length(); i++) {
      count = 1;
      //Take one char at a time
      char c = str.charAt(i);
      // don't count the spaces
      if(c == ' ') 
        continue;
      for(int j = i + 1; j < str.length(); j++) {
        if(c == str.charAt(j)) {
          count++;
          // remove the char so that it is not picked again
          // in another iteration
          str = str.substring(0, j) + str.substring(j+ 1);
        }
      }
      if(count > 1) {
        System.out.println(c + " found " + count + " times");
      }
    }
  }
}

Output

Duplicates in- kakatua parrot is a bird
k found 2 times
a found 5 times
t found 2 times
r found 3 times
i found 2 times
------------
Duplicates in- John was jealous
o found 2 times
a found 2 times
s found 2 times
------------
Duplicates in- rats

Java program to find duplicate characters in a String using HashMap

If you are writing a Java program to find duplicate characters in a String and displaying the repetition count using HashMap then you can store each char of the String as a key and starting count as 1 which becomes the value. In each iteration check if key already exists, if yes then increment the count (by accessing the value for that key).

public class DuplicateChars {

  public static void main(String[] args) {    
    findDuplicateCharsWithCount("kakatua parrot is a bird");
    System.out.println("------------");
    findDuplicateCharsWithCount("John was jealous");
    System.out.println("------------");
    findDuplicateCharsWithCount("rats");
  }
    
  private static void findDuplicateCharsWithCount(String str) {
    System.out.println("Duplicates in- "+ str);
    char[] strArr = str.toCharArray();
    Map<Character, Integer> countMap = new HashMap<>();
    for(char c : strArr) {
      // We don't need to count spaces
      if(c == ' ')
        continue;
      if(countMap.containsKey(c)) {
        countMap.put(c, countMap.get(c) + 1);
      }else {
        countMap.put(c, 1);
      }
    }
    // Displaying the map values
    Set<Map.Entry<Character, Integer>> countSet = countMap.entrySet();
    for(Map.Entry<Character, Integer> entry  : countSet){
      if(entry.getValue() > 1) {
        System.out.println(entry.getKey() + " found " + entry.getValue() + " times");
      }
    }
  }
}

Output

Duplicates in- kakatua parrot is a bird
a found 5 times
r found 3 times
t found 2 times
i found 2 times
k found 2 times
------------
Duplicates in- John was jealous
a found 2 times
s found 2 times
o found 2 times
------------
Duplicates in- rats

Java program to find duplicate characters in a String using Java Stream

you can also use methods of Java Stream API to get duplicate characters in a String. There is a Collectors.groupingBy() method that can be used to group characters of the String, method returns a Map where character becomes key and value is the frequency of that charcter.

Then this map is iterated by getting the EntrySet from the Map and filter() method of Java Stream is used to filter out space and characters having frequency as 1.

Also note that chars() method of String class is used in the program which is available Java 9 onward. It is used to get String characters as IntStream.

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class DuplicateCharCount {

  public static void main(String[] args) {
    String str = "kakatua parrot is a bird";
    duplicateCountInStream(str.chars());
  }
  
  private static void duplicateCountInStream(IntStream stream){
    Map<Character, Long> countMap = stream.mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    countMap.entrySet().stream()
               .filter(es -> !es.getKey().equals(' ') && es.getValue() > 1)
               .forEach(es->{System.out.print("Character- " + es.getKey().toString() + " found ");

                   System.out.println(es.getValue() + " times");
                   });

  }
}

Output

Character- a found 5 times
Character- r found 3 times
Character- t found 2 times
Character- i found 2 times
Character- k found 2 times

That's all for this topic Find Duplicate Characters in a String With Repetition Count Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Convert String to Byte Array Java Program
  2. Add Double Quotes to a String Java Program
  3. Convert String to double in Java
  4. Java Program to Find First Non-Repeated Character in a Given String
  5. Unzip File in Java

You may also like-

  1. Compress And Decompress File Using GZIP Format in Java
  2. How to Create PDF in Java Using OpenPDF
  3. Producer-Consumer Java Program Using ArrayBlockingQueue
  4. Convert double to int in Java
  5. New Date And Time API in Java With Examples
  6. Exception Handling in Java Lambda Expressions
  7. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  8. Spring depends-on Attribute

1 comment:

  1. public static void main(String[] args) {
    // TODO Auto-generated method stub

    String s="aaabbbccc";
    s=s.replace(" ", "");
    char[] ch=s.toCharArray();
    int count=1;
    int match_count=1;
    for(int i=0;i<=s.length()-1;i++){

    if(ch[i]!='0'){

    for(int j=i+1;j<=s.length()-1;j++){

    if(ch[i]==ch[j])
    {
    match_count++;
    ch[j]='0';
    }
    else{
    count=1;
    }
    }
    if(match_count>1&& ch[i]!='0'){
    System.out.println("Duplicate Character is "+ch[i]+" appeared "+match_count +" times");
    match_count=1;
    }
    }
    }
    }

    ReplyDelete