5
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

user1918566
  • 221
  • 1
  • 5
  • 18

4 Answers4

2
 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

Community
  • 1
  • 1
Erick Maia
  • 196
  • 6
2

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.

shmosel
  • 49,289
  • 6
  • 73
  • 138
0
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String str = "abcdaa";
    String result = dups(str);
    System.out.println(result);
}
public static String dups(String str){
    HashSet hs = new HashSet();
    String strss = "";
    char[] ch = str.toCharArray();
    for(int i=0; i < ch.length;i++){
        if(hs.add(ch[i])){
            strss +=ch[i];
        }
    }
    return strss;
}
Vasyl Lyashkevych
  • 1,920
  • 2
  • 23
  • 38
0

If you can use a third-party library, the CharAdapter class in Eclipse Collections can solve the problem.

String str = "abcdaa";
CharAdapter distinct = CharAdapter.adapt(str).distinct();
System.out.println(distinct);

You can see what the code does here. Using a java.util.HashSet will box the char values as Character objects. The distinct method in CharAdapter uses a CharHashSet which does not need to box the char values.

Note: I am a committer for Eclipse Collections.

Donald Raab
  • 6,458
  • 2
  • 36
  • 44