×

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

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

4 minutes read.

Process and Thread in Java

Process It is a program that is running on your computer. The process is a heavy-weight, which takes memory separately to other processes. The process may be a small background task like spell-checker; it...

11 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Dictionary in Java

Dictionary in Java The Dictionary class represents a key-value relation which maps keys to values. In Dictionary class, every key and every value is an object. It is an abstract class associated with...

2 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.