Home > database >  I am converting a String in to a set of character in java but I want to keep all the data arranged a
I am converting a String in to a set of character in java but I want to keep all the data arranged a

Time:08-03

 String removeDups(String S) {
    String str = "";
    Set<Character> s1 = new HashSet<Character>();
    for(int i =0; i<S.length(); i  ){
        char ch = S.charAt(i);
        s1.add(ch);
    }
    List<Character> l1 = new ArrayList<>();
    l1.addAll(s1);
    for(int i =0; i<l1.size(); i  ){
        str = str l1.get(i);
    }
    
    return str;
}

/* Here return str; will return the character that occoured once but not in proper order for eg: if the input String is "zvvo" we will get output "vzo" but I want output "zvo" */

CodePudding user response:

You could use a LinkedHashSet instead of a HashSet, but in my opinion it is cleaner to test if you have encountered the character before and use a StringBuilder. Like,

String removeDups(String in) {
    StringBuilder sb = new StringBuilder();
    Set<Character> set = new HashSet<>();
    for (int i = 0; i < in.length(); i  ) {
        char ch = in.charAt(i);
        if (set.add(ch)) {
            sb.append(ch);
        }
    }
    return sb.toString();
}
  • Related