How to Remove Duplicates from a String in Java Using Hashing?
Last Updated :
12 Feb, 2024
Working with strings is a typical activity in Java programming, and sometimes we need to remove duplicate characters from a string. Using hashing is one effective way to do this. By assigning a unique hash code to each element, hashing enables us to keep track of unique items. This article will examine the use of hashing in Java to eliminate duplicates from a string.
Approach
Preserving a set of unique characters is the primary motivation for using hashing to eliminate duplicates from a string. The hash code for each character in the string may be found by iterating over it and storing unique characters in a hash set. We effectively filter out duplicates by doing this.
Example to Remove Duplicates from a String in Java Using Hashing
Let’s look at a simple example in which we want to use hashing to eliminate duplicates from the term “programming”.
Java
import java.util.HashSet;
public class RemoveDuplicatesExample {
public static String removeDuplicates(String input) {
HashSet<Character> uniqueChars = new HashSet<>();
StringBuilder result = new StringBuilder();
for ( char ch : input.toCharArray()) {
if (uniqueChars.add(ch)) {
result.append(ch);
}
}
return result.toString();
}
public static void main(String[] args) {
String inputString = "programming" ;
String result = removeDuplicates(inputString);
System.out.println( "Original String: " + inputString);
System.out.println( "String after removing duplicates: " + result);
}
}
|
Output
Original String: programming
String after removing duplicates: progamin
Explanation of the above Program:
- The removeDuplicates function stores unique characters observed in a HashSet (uniqueChars) after receiving a string as input.
- It uses add() to run over each character in the input text and determine whether or not it already exists in the HashSet.
- The character is added to the StringBuilder result if it is unique.
- Converting the StringBuilder to a string yields the desired outcome.
Share your thoughts in the comments
Please Login to comment...