简体   繁体   中英

how do you remove repeated strings in java?

Input: 3 3 2 1

Desired output: 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. Just build a new string from the 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. Check the below statement.

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

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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