Java program to delete duplicate characters from a given String


The interface Set does not allow duplicate elements, therefore, create a set object and try to add each element to it using the add() method in case of repetition of elements this method returns false −

If you try to add all the elements of the array to a Set, it accepts only unique elements so, to find duplicate characters in a given string

  • Convert it into a character array.
  • Try to insert elements of the above-created array into a hash set using add method.
  • If the addition is successful this method returns true.
  • Since Set doesn't allow duplicate elements this method returns 0 when you try to insert duplicate elements
  • Print those elements

Example

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class DuplicateCharacters {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the required string value ::");
      String reqString = sc.next();
      char[] myArray = reqString.toCharArray();
      System.out.println("indices of the duplicate characters in the given string :: ");
      Set set = new HashSet();

      for(int i=0; i<myArray.length; i++){
         if(!set.add(myArray[i])){
            System.out.println("Index :: "+i+" character :: "+myArray[i]);
         }
      }
   }
}

Output

Enter the required string value ::
malayalam
indices of the duplicate characters in the given string ::
Index :: 3 character :: a
Index :: 5 character :: a
Index :: 6 character :: l
Index :: 7 character :: a
Index :: 8 character :: m

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 13-Mar-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements