TomM12
TomM12

Reputation: 55

Built in method for removing duplicates in a string array

Is there a java built-in method for removing duplicates ? (array of strings)

Maybe using a Set ? in this case how can I use it ?

Thanks

Upvotes: 0

Views: 1763

Answers (1)

Dexters
Dexters

Reputation: 2495

Instead of an array of string, you can directly use a set (in this case all elements in set will always be unique of that type) but if you only want to use array of strings , you can use the following to save array to set then save it back.

import java.util.Arrays;
import java.util.HashSet;

public class HelloWorld{

     public static void main(String []args)
     {
        String dupArray[] = {"hi","hello","hi"};
        dupArray=removeDuplicates(dupArray);

        for(String s: dupArray)
                 System.out.println(s);
     }

    public static String[] removeDuplicates(String []dupArray)
    {
        HashSet<String> mySet = new HashSet<String>(Arrays.asList(dupArray));
        dupArray = new String[mySet.size()];
        mySet.toArray(dupArray);
        return dupArray;
    }
}

Upvotes: 1

Related Questions