Remove Duplicate Character From String in Java using HashMap

 

In this Blog we are going to learn how to remove Duplicate Characters from a string in java using Hashmap

Code :

package learningJava;
import java.util.*;
public class Learnig {
public static void main(String[] args) {
String s = "aabbcaddbe"; //input String 
HashMap<Character,Integer> map = new HashMap<>();
String ans=""; //store our answer 
char[] input = s.toCharArray(); //converting string into array
for(int i=0;i<input.length;i++) {
if(!map.containsKey(input[i])) {
map.put(input[i], 1);
ans= ans+ input[i];
}
else {
map.put(input[i],1);
}
}
System.out.print(ans);
}
}


Output

abcde


Post a Comment

0 Comments