In this article, we will discuss steps and execution program to delete/remove all duplicate characters/occurrences from given String
Remove duplicate characters from String:
Steps:
- Create LinkedHashSet to maintain insertion-order
- Convert given/test String into character-array using toCharArray(); method
- Iterate through char[] array using enhanced for-each loop
- Leave spaces, as it isn’t considered while deleting/removing duplicate occurrences/characters
- While iterating, check whether character already present in LinkedHashSet
- If not present in LinkedHashSet, then add that particular character into LinkedHashSet using add(); method; otherwise leave it, as it is duplicate character/occurence
- finally, print to console
RemoveDuplicateFromString.java
package in.bench.resources.collection;
import java.util.LinkedHashSet;
import java.util.Set;
public class RemoveDuplicateFromString {
public static void main(String[] args) {
// sample test string
String testStr = "SSS FFF GG RR";
// Step 1: create LinkedHashSet to maintain insertion-order
Set<Character> lhSet = new LinkedHashSet<Character>();
// Step 2: convert String into character-array
// using toCharArray() method
char[] chArray = testStr.toCharArray();
// Step 3: iterate through char[] array
for(char ch : chArray) {
// Step 4: leave spaces
if(ch != ' '){
// Step 5: check whether char already present in LHSet
boolean checkChar = lhSet.contains(ch);
// Step 6: if not present, then add
if(!checkChar) {
lhSet.add(ch);
}
}
}
// Step 7: print to console
System.out.println("After removing duplicate : " + lhSet);
}
}
Output:
After removing duplicate : [S, F, G, R]
Related Articles:
- Java- How to count duplicate elements of ArrayList
- Java – Various ways to remove duplicate elements from Arrays in 5 ways
- Java – How to find duplicate in String Arrays ?
- Java – Remove duplicate elements from ArrayList
- Java – How to remove duplicate elements of ArrayList maintaining insertion order
- Java – Conversion of ArrayList into HashSet to remove duplicate elements
- Java 8 – How to find duplicate and its count in a Stream or List ?
- Java 8 – How to remove duplicates from ArrayList
- Java 8 – How to remove duplicates from LinkedList
- Java 8 – How to find duplicate and its count in an Arrays ?
- Java 8 – How to remove duplicate from Arrays ?
- Java 8 – Various ways to remove duplicate elements from Arrays
- Java 8 – How to remove an entry from HashMap by comparing keys
- Java 8 – How to remove an entry from HashMap by comparing values
Happy Coding !!
Happy Learning !!