xyz
xyz

Reputation: 8927

How to get rid of duplicate entries in a comma separated string in java?

I have a string places="city,city,town". I need to get "city,town". Basically get rid of duplicate entries in the comma separated string.

places.split(","); will give me array of String. I wonder, if I can pass this array to a HashSet or something, which will automatically get rid of duplicates, but trying something like:

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

gives the error:

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

Any neat way of achieving this, preferably with least amount of code?

Upvotes: 3

Views: 10384

Answers (6)

kishore.jannarapu
kishore.jannarapu

Reputation: 89

It is similar to this and slightly better readability. Just splitting the string with comma which returns Array of strings and find the distinct values in the array and join the elements using comma, which returns a string without duplicate values.

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

Upvotes: 1

Vaibhav Sharma
Vaibhav Sharma

Reputation: 1742

Another way of doing this in Java 8 would be:

Lets say you have a string str which is having some comma separated values in it. You can convert it into stream and remove duplicates and join back into comma separated values as given below:

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

This will give you a String str without any duplicate

Upvotes: 2

TanvirChowdhury
TanvirChowdhury

Reputation: 2445

 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);

or you can use linkedHashset

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

Upvotes: 0

vaughandroid
vaughandroid

Reputation: 4374

If you care about the ordering I'd suggest you use a LinkedHashSet.

LinkedHashSet test = new LinkedHashSet(Arrays.asList(a.split(",")));

Upvotes: 3

Chandra Sekhar
Chandra Sekhar

Reputation: 19500

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

Upvotes: 2

Nishant
Nishant

Reputation: 55866

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

this is because HashSet does not have a constructor that expects an array. It expects a collection, which is what I am doing here by Arrays.asList(s.split(","))

Upvotes: 11

Related Questions