Here we will learn the program to remove all the duplicate characters from string ,suppose we have string "Malayalam" then output will be "Mym". In given string we have duplicate character like 'a', and 'l' , so the output will become "Mym".
In this program we have used LinkedHashMap to maintain character insertion order and to find the duplicate character. And we have store character as key in Map to find duplicate character.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; public class RemoveDuplicateCharacter { public static void removeWithCollection(String str){ Map<Character, Integer> map = new LinkedHashMap<>(); for(int i=0;i<str.length();i++){ if(map.containsKey(str.charAt(i))){ map.put(str.charAt(i), map.get(str.charAt(i))+1); } else{ map.put(str.charAt(i), 1); } } String output = ""; String duplicateChar = ""; for(Entry<Character, Integer> en : map.entrySet()){ if(map.get(en.getKey()) == 1){ output+=en.getKey(); } else{ duplicateChar+=en.getKey(); } } System.out.println("Original String :\t"+str+"\nDuplicate Characters :\t"+duplicateChar+"\nOutput String :\t\t"+output); } public static void main(String[] args) { RemoveDuplicateCharacter.removeWithCollection("Pushkar Khosla"); System.out.println(); RemoveDuplicateCharacter.removeWithCollection("Malayalam"); } } |
Output:
Original String : Pushkar Khosla
Duplicate Characters : sha
Output String : Pukr Kol
Original String : Malayalam
Duplicate Characters : al
Output String : Mym
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.
This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.
This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.
Java I/O Tutorial

No comments:
Post a Comment