Remove duplicates from an array of strings. - Android java.lang

Android examples for java.lang:array element remove

Description

Remove duplicates from an array of strings.

Demo Code

import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Locale;

public class Main{

    /**/* w  ww .  ja va 2s  .co m*/
     * Remove duplicates from an array of strings.
     *
     * This method will always keep the first occurrence of all strings at their position
     * in the array, removing the subsequent ones.
     */
    public static void removeDupes(final ArrayList<CharSequence> suggestions) {
        if (suggestions.size() < 2)
            return;
        int i = 1;
        // Don't cache suggestions.size(), since we may be removing items
        while (i < suggestions.size()) {
            final CharSequence cur = suggestions.get(i);
            // Compare each suggestion with each previous suggestion
            for (int j = 0; j < i; j++) {
                CharSequence previous = suggestions.get(j);
                if (TextUtils.equals(cur, previous)) {
                    suggestions.remove(i);
                    i--;
                    break;
                }
            }
            i++;
        }
    }

}

Related Tutorials