如何在Java中消除逗号分隔字符串中的重复条目?

3

我有一个字符串places="city,city,town"。我需要得到"city,town",也就是说,要在逗号分隔的字符串中去掉重复的条目。

使用places.split(",");可以获得字符串数组。我想知道,是否可以将这个数组传递给HashSet或类似的东西,它会自动去除重复项,但尝试这样做:

HashSet test=new HashSet(a.split(","));

出现错误:

cannot find symbol
symbol : constructor HashSet(java.lang.String[])

有没有一种简洁的方法来实现这个,最好是用尽可能少的代码?
6个回答

11
    HashSet<String> test=new HashSet<String>(Arrays.asList(s.split(",")));

这是因为 HashSet 没有期望接收一个数组的构造函数。我在这里使用 Arrays.asList(s.split(",")) 来传递一个集合,这是 HashSet 所期望的。


谢谢。可行。有没有快速实现连接操作的方法?也就是说,将哈希集合条目用逗号连接起来。 - xyz
唉,如果你用Python或Scala问这个问题就好了。在Java中,它是String finalString = "";for(String s: test)finalString = finalString +s+",";if(finalString.length()>0) finalString = finalString.substring(0, finalString.length()-1); - Nishant
String newTagVals = StringUtils.join(test.toArray(), COMMA);将test数组中的元素以逗号分隔符连接成一个字符串,赋值给newTagVals变量。 - Satheesh Cheveri

3
如果您关心排序,我建议您使用 LinkedHashSet
LinkedHashSet test = new LinkedHashSet(Arrays.asList(a.split(",")));

2
String s[] = places.split(",");
HashSet<String> hs = new HashSet<String>();
for(String place:s)
    hs.add(place);

2

在Java 8中另一种方法是:

假设您有一个包含一些逗号分隔值的字符串str。您可以将其转换为流并删除重复项,然后按照以下方式加入回逗号分隔值:

String str = "1,2,4,5,3,7,5,3,3,8";
str = String.join(",",Arrays.asList(str.split(",")).stream().distinct().collect(Collectors.toList()));

这将为您提供一个不带重复的字符串str

0
 String[] functions= commaSeperatedString.split(",");

            List<String> uniqueFunctions = new ArrayList<>();

            for (String function : functions) {
                if ( !uniqueFunctions.contains(function.trim())) {
                    uniqueFunctions.add(function.trim());
                }
            }
            return String.join(",",uniqueFunctions);

或者您可以使用 LinkedHashSet

LinkedHashSet result = new LinkedHashSet(Arrays.asList(functions.split(",")));


0

这与this类似,但可读性稍好。 只需使用逗号拆分字符串,返回字符串数组并查找数组中的不同值,然后使用逗号连接元素,即可返回一个没有重复值的字符串。

String noDups = Arrays.stream(input.split(",")).distinct().collect(Collectors.joining(","));

1
我建议您不要仅仅发布代码作为答案,还应该提供解释您的代码是如何解决问题的。带有解释的答案通常更有帮助和更高质量,并且更有可能吸引赞同。 - Mark Rotteveel
此外,您的答案与此答案非常相似,只是您直接从流中连接,而不是先转换为列表。 - Mark Rotteveel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接