Remove duplicate characters from String in Java

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 in Java :

Steps:

  1. Create LinkedHashSet to maintain insertion-order
  2. Convert given/test String into character-array using toCharArray(); method
  3. Iterate through char[] array using enhanced for-each loop
  4. Leave spaces, as it isn’t considered while deleting/removing duplicate occurrences/characters
  5. While iterating, check whether character already present in LinkedHashSet
  6. If not present in LinkedHashSet, then add that particular character into LinkedHashSet using add(); method; otherwise leave it, as it is duplicate character/occurence
  7. 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]

 

Happy Coding !!
Happy Learning !!

Java - How to uppercase every duplicate character in String ?
Interview program on String using null