Remove duplicate values from a string in java

Viewed 35761

Can anyone please let me know how to remove duplicate values from

String s="Bangalore-Chennai-NewYork-Bangalore-Chennai"; 

and output should be like

String s="Bangalore-Chennai-NewYork-";

using Java..

Any help would be appreciated.

14 Answers

A little late to the game, but I would simply use a HashMap. It's easy to understand and has quick lookups on the keys, might not be the best way but it's still a good answer IMO. I use it all the time when I need to format quick and dirty:

                    String reason = "Word1 , Word2 , Word3";
                    HashMap<String,String> temp_hash = new HashMap<String,String>();
                    StringBuilder reason_fixed = new StringBuilder();
                    //in:
                    for(String word : reason.split(",")){
                        temp_hash.put(word,word);
                    }
                    //out:
                    for(String words_fixed : temp_hash.keySet()){
                        reason_fixed.append(words_fixed + " , ");
                    }
                    //print:
                    System.out.println(reason_fixed.toString());
StringBuilder builderWord = new StringBuilder(word);
for(int index=0; index < builderWord.length(); index++) {
    for(int reverseIndex=builderWord.length()-1; reverseIndex > index;reverseIndex--) {
        if (builderWord.charAt(reverseIndex) == builderWord.charAt(index)) {
            builderWord.deleteCharAt(reverseIndex);
        }
    }
}
return builderWord.toString();
Related