Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicates in array with arraylist fails

I wanted to remove duplicates from an array, by using an array list. The code seems to work fine for all cases except when String[]array contains three copies of an element. Why does this problem happen and how to fix it ?

Test input - 
array = {"D22", "D22", "D22"};

Output = 
D22
D22

Expected output = 
D22

public static String[] removeDuplicates(String [] array){
    String [] noDups = null;
    ArrayList<String> copy = new ArrayList<String>();
    String first = "";
    String next = "";

    for(String s: array){
        copy.add(s.trim());//Trimming
    }

    for(int i = 0; i < copy.size(); i++){

        for(int j = i + 1; j < copy.size(); j++){

            first = copy.get(i);
            next = copy.get(j);

            if(first.equals(next)){
                copy.remove(j);
            }

        }


    }

    noDups = copy.toArray(new String[copy.size()]);

    for(String s: noDups){
        System.out.println(s);

    }

    return noDups;
}
like image 231
Trojan.ZBOT Avatar asked Sep 09 '26 15:09

Trojan.ZBOT


1 Answers

Try this, it is most simpler:

public static String[] removeDuplicates(String[] array) {
    ArrayList<String> res = new ArrayList<String>();

    for (String str : array) {
        if (!res.contains(str)) {
            res.add(str);
        }
    }
    return res.toArray(new String[res.size()]);
}

public static void main(String[] args) {
    String[] arr = {"D22", "D22", "D22"};
    String[] res = removeDuplicates(arr);
    for (String string : res) {
        System.out.println(string);
    }
}

Output: D22

like image 116
Masudul Avatar answered Sep 12 '26 04:09

Masudul