0

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

2

1 Answer 1

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

To my knowledge hashset, does not guarantee an order , why not try LinkedHashSet ?
OP did not mention ordering is required

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.