I am not sure how to explain this so I will give an example. If I were to have two arrayList like the one listed below:

ArrayList<String> java = new ArrayList<String>();
        java.add("1");
        java.add("2");
        java.add("2");
        java.add("4");
        ArrayList<String> lava = new ArrayList<String>();
        lava.add("0");
        lava.add("2");
        lava.add("5");
        lava.add("4");

how would i remove the duplicates, like in ArrayList lava there is a 2, then all the elements with a value of 2 should be removed. How would I do this?

One way would be to loop through the first arraylist's elements one by one and see if the second arraylist contains that element and if it does, remove it. Since there can be more than one match you'd need a loop to continue checking until all were removed.

Read the API doc for ArrayList to see all the methods that are available and useful.

Edited 4 Years Ago by NormR1

Here is what I did:

for(int i = 0; i < list1.size() - 1; i++){
            if(list1.get(i).compareTo(list2.get(i)) == 0){
                list1.remove(list2.get(i));
            }
        }

But it does not work

But it does not work

Please explain. Post a print out of the contents of the lists after the code executes.
Also add println statements that print out when a match is found and that print out the results of the remove() method (it returns a boolean).

Can you post a small complete program that compiles, executes and shows the problem?

Your code is only comparing elements at the same location in the two lists by using the same index i for both lists.

Also try using some of the other ArrayList methods.

Edited 4 Years Ago by NormR1

for(int i = 0; i < list1.size() - 1; i++){
        if(list1.get(i).compareTo(list2.get(i)) == 0){
            list1.remove(list2.get(i));
        }
    }

once an element is removed from either list their sizes will be different from the other. So you can't compare the remaining elements of a list with the others original position

You could use a nested loop to check if a value from a list is present with every element from the other

@godzab:
In the example you gave, do you want to remove the 2 from java. lava, or both? What if there are duplicate entries in either one of those two lists?

ps: Guys - what's all this fortran-style for looping and hand-coded searches? This is Java, we have enhanced for loops, and ArrayList has a remove method that does exactly what's needed. Removing every object from list2 that is present in list1 is a single line of code - a "do" a "while" and a single method call.

This question has already been answered. Start a new discussion instead.