简体   繁体   English

你如何删除java中的重复字符串?

[英]how do you remove repeated strings in java?

Input: 3 3 2 1输入:3 3 2 1

Desired output: 3 2 1期望输出:3 2 1

(the spaces should remain) (空格应保留)

I tried to use this method but it does not work我尝试使用此方法但它不起作用

public String filterRepeats(String s) 
{
        return new LinkedHashSet<String(Arrays.asList(s.split("\\s"))).toString();
}

Your code works.您的代码有效。 If you are concerned about the brackets of the toString method.如果您担心toString方法的括号。 Just build a new string from the LinkedHashSet .只需从LinkedHashSet构建一个新字符串。 For example:例如:

public String filterRepeats(String s) {
        LinkedHashSet<String> set = new LinkedHashSet<String>(Arrays.asList(s.split("\\s")));

        String result = "";
        for (String elt : set) {
            result += elt + " ";

        }
        // trim last space
        result = res2.substring(0, result.length()-1);
        return result;

}

Caution!警告! The below code is expensive, If you just need it work then you can do it in the below way.下面的代码很昂贵,如果你只是需要它工作,那么你可以通过下面的方式来完成。

String a = "a b c d a b c";
Set<String> foo = new LinkedHashSet<>(Arrays.asList(a.split(" ")));
a = foo.toString().replaceAll("\\[|\\]","").replaceAll(","," ");

If you are using Java 8, streams will simplify your job, you need not use the replaceAll method at all.如果您使用的是 Java 8,流将简化您的工作,您根本不需要使用replaceAll方法。 Check the below statement.检查下面的语句。

a = foo.stream().collect(Collectors.joining(" "));

Cheers!干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM