×

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the string can be removed in many ways. Some of the ways include:

  • Using for loop
  • By sorting method
  • Hashing
  • IndexOf()

Hence, many ways exist to remove duplicate characters from the given string.

These different methods have varying time complexities. We can use them based on request.

Using for loop

It is one of the easiest and simple ways to remove duplicate characters from the given string.

Steps for removing the duplicate keys using for loop.

  1. The given array is converted into a character array as the division of the Characters.
  2. Find the length of the array.
  3. Create a function for calling the duplicate elements in the array by passing the character as a parameter.
  4. Using for loop, visit all characters of the array to search the duplicate element.
  5. Check the character present in the string.

Example

import java.io.*;
import java.util.*;
class RemoveDuplicates
{
  //creating method for removing duplicate characters
   static void  remove duplicate(char strings[], int len)
 {
  // declaring value for sttoring index
  int n=0;
  for(int i=0;i<len;i++)
 {
   // checking whether the character is present
     int j;
     for(j=0;j<i;j++)
     {
        if(strings[i]==strings[j])
       {
           break;
        }
     }
   //if it was not present then add it result
   if(j==i)
   {
      strings[n++]=strings[i];
   }
 }
 System.out.println(String.valueOf(Arrays.copyOf(strings,n)));
}
//main section
public static void main(String s[])
{
  String info=“java is a good programming language”;
   //Converting to character array
  char strings[]=info.toCharArray();
 //finding length of character array
  int lengt=strings.length;
  // calling method for removal of characters
   removeDuplicate(strings,lengt);
}
}

Output

Java Program to remove duplicate characters from a string

Using Sorting method

The sorting method is one of the methods for removing duplicate characters in the string.

This method is faster as compared to the for-loop method. In this, first, the array is sorted.

And the duplicated elements are present adjacent to each other. Performing this operation includes:

  1. Sort the given string
  2. Take the current element and compare it with the remaining elements in the loop.
  3. The characters present for more than once can be removed.
  4. The technique does not maintain the authentic order of the input string. String order is different from initial.

A simple java Program using sorting techniques.

Example

import java.util.Arrays; 
import java.util.*;
public class Main 
{   
      static void removeDuplicates(String str)   
    {   
        //to find next character of string given
        int ind1 = 1;          
          
        // to find next character in the resultant string 
        int ind2 = 1;  
            
        // converting string to indivial(Chaaracter array)  
        char arr[] = str.toCharArray();   
            
        //Checking whether the character is present in it or not
while (ind1 != arr.length)   
        {   
            if(arr[ind1] != arr[ind1-1])   
            {   
                arr[ind2] = arr[ind1];   
                ind2++;   
            }   
            ind1++;   
              
        }   
        
        str = new String(arr);  
        System.out.println(str.substring(0, ind2));   
    }   
  //method for storing the sorted string  
    static String sortString(String str)   
    {   
       // String is converted to character 
       char temp[] = str.toCharArray();   
         
       //sort array using array's sort () method  
       Arrays.sort(temp);   
         
       //String from character array   
       str = new String(temp);   
           
       // result 
       return str;   
    }   
        
    public static void main(String[] args)   
    {   
        //Declaring a default string   
        String str = “Java is best programming language";   
          
        //calling method for storing the sorted string 
        String newString = sortString(str);  
        System.out.println(newString);  
          
        // removeDuplicates() method for removal of same characters  
        removeDuplicates(newString);  
    }   
}  

Output

Java Program to remove duplicate characters from a string

Using Hashing method

Another way to get rid of duplicate characters from a string is hashing. By using hashing, we can do that. We will use the subsequent steps to take away duplicates by using hashing:

  • Inside the main() approach, we can create a string from which we ought to eliminate replica characters.
  • We can call the removeDuplicates() approach and surpass the string from which we need to eliminate duplicates.
  • Inside the removeDuplicates() technique, create a LinkedHashSet of character kind. LinkedHashSet includes a distinct detail. This set contains distinct elements. So that duplicate characters are removed. Ultimately, we print all of the characters of the LinkedHashSet.
  • It includes characters in insertion order.
  • This can be done using a simple program.

Example

import java.util.*;   
  
//Class for accessing methods for removing duplicate characters
class Main 
{   
    //Create a method removeDuplicates() for finding unique characters using Hashing  
    static void removeDuplicates(String str)   
    {     
        //HashSet class creation   
        LinkedHashSet<Character> set = new LinkedHashSet<>();   
        //each character is added to set   
        for(int i=0;i<str.length();i++)   
            set.add(str.charAt(i));   
            
        // string after removing same characters   
        for(Character ch : set)   
            System.out.print(ch);   
    }   
        
    //main() 
    public static void main(String args[])   
    {   
        //Default value is assigned to str  
        String str = "java is good programming language";   
        //calling method by passing string as a parameter   
        removeDuplicates(str);   
    }   
}  

Output:

Java Program to remove duplicate characters from a string

index() method

This method is used for the removal of duplicate characters from a string.

It uses index values to find distinct characters from the given string.

The steps followed in this are:

  • The main() method contains a string for finding unique characters.
  • The removeDuplicates() mehod is called, and the string is passed as an argument.
  • The initial string length is calculated in the removeDuplicates() method.
  • All characters are checked in the string.
  • This method returns -1 if the element can’t be present in the string. So it was added to the resulting string.

Example

// import classes and packages   
import java.util.*;   
  
//create RemoveDuplicatesIndex class to remove characters   
class RemoveDuplicatesIndex {   
        
    // Create removeDuplicates() for removing duplicate characters by index()  
    public static void removeDuplicates(String str)   
    {   
        //Empty string for storing 
        String newstr = new String();   
          
        //length is calculated using length() function  
        int length = str.length();   
            
        //visiting each and every character of string  
        for (int i = 0; i < length; i++)    
        {   
            // Index value of ith position is stored
            char charAtPosition = str.charAt(i);   
                
            // check the charAtPosition  index. if it returns true add it to result
            if (newstr.indexOf(charAtPosition) < 0)   
            {   
                newstr += charAtPosition;   
            }   
        }   
        //Unique character string
        System.out.println(newstr);  
    }   
    
    // main()  
    public static void main(String[] args)   
    {   
        // default value   
        String str = "Java is a object oriented programming language";   
        //calling method removeDuplicates method   
        removeDuplicates(str);   
    }   
}  

Output

Java Program to remove duplicate characters from a string

The above four methods can be used to remove duplicate characters. Any of the four methods can be used according to our choice.


Related Topics

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Java Math max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.