Delete duplicate strings in string array

user1339752 picture user1339752 · Apr 28, 2012 · Viewed 77k times · Source

I am making a program based on string processing in Java in which I need to remove duplicate strings from a string array. In this program, the size of all strings are same.

The 'array' which is a string array contains a number of strings in which two strings resemble each other. So using the below code the duplicate string must get removed but it is not removed.

How to remove the duplicate strings?

I am using the following code.

    for(int s=0;s<array.length-1;s++)
    {
        for(int m=0;m<array.length;m++)
        {
                for(int n=0;n<array[m].length();n++)
                {   
                    if(array[s].charAt(n)==array[m].charAt(n))
                    {
                      continue;
                    }
                    else 
                break;
        } 
        if(n==array[m].length())
        {
            ArrayUtils.removeElement(array, array[s]);
        }
    }

Answer

Garrett Hall picture Garrett Hall · Apr 28, 2012

This will work

array = new HashSet<String>(Arrays.asList(array)).toArray(new String[0]);

or just use a HashSet instead of an array.