Hello Folks,
As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a java program to Remove Duplicate Characters From Word Using Collection Concept.
Problem Statement:
Remove all duplicate characters from given word. Keep the order of char as it appears.
User Input – abcabcabcabc
Output: abc
Problem Solution:
Step by step logic:
- Since we need to find duplicate characters in a word, we need to extract all characters from word. We can use toCharArray() method of String class to get an array of chars of words.
- We need to store chars in a container who does not allow duplicates and maintains insertion order. We can use LinkedHashSet container for the same.
- Iterate char array and add each char in to LinkedHashSet container . After iteration, container will have only single occurrence of each char.
- Now we need to form a string using chars of container. We can use StringBuilder or StringBuffer for the same.
Java Program:
package StringPrograms; import java.util.LinkedHashSet; import java.util.Scanner; public class RemoveDuplicatesCharFromWord { public static String removeDuplicateCharFromGivenWord(String inputWord) { /* * Since we need to check for duplicate chars in word, we must need to extract * each char of word. And the best way is to convert in to char array. */ inputWord = inputWord.toLowerCase(); char charsOfWord[] = inputWord.toCharArray(); /* * Since we need to remove duplicates and maintain the insertion order as well, * we will use LinkedHashSet with Generic as Character. */ LinkedHashSetwordWithoutDuplicate = new LinkedHashSet<>(); /* * Iterate char array and add in to container. Duplicate will not be added. */ for (Character c : charsOfWord) wordWithoutDuplicate.add(c); /* * We need to create word by appending all unique characters in sequence. SInce * String is immutable, we need to use StringBuilder or StringBuffer. */ StringBuilder finalOutput = new StringBuilder(); for (Character ch : wordWithoutDuplicate) finalOutput.append(ch); // Returning final output return finalOutput.toString(); } public static void main(String[] args) { // User input to trim spaces Scanner sc = new Scanner(System.in); System.out.println("Please enter the word to remove duplicate chars:"); String userInput = sc.nextLine(); sc.close(); System.out.println("You entered : \"" + userInput + "\""); System.out.println( "String after removing duplicate chars: \"" + removeDuplicateCharFromGivenWord(userInput) + "\""); } }
Output:
Please enter the word to remove duplicate chars:
abcabcabcabc
You entered : “abcabcabcabc”
String after removing duplicate chars: “abc”
===================================================
Please enter the word to remove duplicate chars:
banana
You entered : “banana”
String after removing duplicate chars: “ban”
You can run above program for multiple inputs and if it fails for any condition, let me know.
#HappyCoding