Remove duplicate values from a string in java

前端 未结 14 2655
刺人心
刺人心 2020-12-06 05:26

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

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

and output sh

14条回答
  •  余生分开走
    2020-12-06 06:20

    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 temp_hash = new HashMap();
                        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());
    

提交回复
热议问题