public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "abcdaa";
dups(str);
}
public static void dups(String str){
HashSet hs = new HashSet();
char[] ch = str.toCharArray();
for(int i=0; i < ch.length;i++){
hs.add(ch[i]);
}
System.out.println(hs);
}
The above code return Output: [a,b,c,d]
But I want to print the Set values into a string so I can return a string value return value looks like this:Expected Output: abcd
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "abcdaa";
dups(str);
}
public static void dups(String str) {
HashSet<Character> hs = new HashSet<Character>();
char[] ch = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ch.length; i++) {
if(hs.add(ch[i])){
sb.append(ch[i]);
}
}
System.out.println(sb);
}
EDIT
public static void dups(String str) {
HashSet<Character> hs = new HashSet<Character>();
StringBuilder sb = new StringBuilder();
for (Character character : str.toCharArray()) {
if(hs.add(character)){
sb.append(character);
}
}
System.out.println(sb);
}
I can't think a better way to do this... It's better use StringBuilder instead of String, check this answer https://stackoverflow.com/a/1532483/6949032
Not sure why no one had mentioned this yet, but it's pretty simple in Java 8:
System.out.println(String.join("", hs));
Note that if you want to preserve the original order, you'll need to use LinkedHashSet
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With