How to convert a Set containing values ​​to a string

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);
    }

Above code return Output: [a, b, c, d]

But I want to print the Set values ​​in the string to return the return value of the string value as follows: Expected result: abcd

+4
source share
4 answers
 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 don't think this is the best way to do this ... Better to use StringBuilder instead of String, check this answer fooobar.com/questions/4042 / ...

+2
source
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;
}
0
source

, CharAdapter Eclipse Collections .

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

, . java.util.HashSet char Character. CharAdapter CharHashSet, char.

. Eclipse.

0

, , Java 8:

System.out.println(String.join("", hs));

: , LinkedHashSet.

0

Source: https://habr.com/ru/post/1677019/


All Articles