Skip to content
Advertisement

ArrayList Deduplication Problem Questions

I’m curious about removing duplicate data from an ArrayList.

Arraylist<String> a = new ArrayList<>();
Arraylist<String> b = new ArrayList<>();
    
a.add("0");
a.add("1");
a.add("2");
a.add("3");
a.add("4");
a.add("4");
a.add("1");
    
b.add("5");
b.add("6");
b.add("7");
b.add("8");
b.add("9");
b.add("10");
b.add("11");
    
for (int i = 0; i < a.size(); i++ {     
    for (int j = 0; j < a.size(); j++) {
            
        if (a.get(i).equals(a.get(j)) {
    
            a.remove(j);
            b.remove(j);
        }
    }
}

Duplicate values in a must be removed. I also want to remove values at the same index number in b. The problem with this is that the size of a and b keeps getting smaller

Is there any good way?

Advertisement

Answer

From my understanding, you are trying to find the duplicate value to remove it, get its index in and from a, and then remove the value in b at that index. One big problem is that you are modifying the array AS you are trying to find the duplicated value this can cause a lot of problems. Moreover, the cause of a getting smaller (so is b) is because of

 a.remove(j);
 b.remove(j);

with the .remove() it will resize the ArrayList a and b. A way you can preserve the order and size of the array is to keep track of how many times you have removed the duplicate values and add the empty string again after the removal.

int charPos = 0;
for(int i = 0; i < a.size(); i++ {
   
  for(int j = 0; j < a.size(); j++) {
        
        if(a.get(i).equals(a.get(j)){

             a.remove(j);
             b.remove(j);
             charPos++;
        }

   }
}

for(int i = 0; i < charPos; i++) {
        a.add("");
        b.add("");
}

Your question definitely needs further clarification on what you’re allowed to do and what not. It’s very boarded right now. If possible please provide your expected output for the example you have given.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement