dearn44
dearn44

Reputation: 3432

Remove only first instance of duplicate values from two ArrayLists

I have two lists that might look like this:

A: {1 3 1 2}
B: {1 3}

I would like to remove the elements of list B from list A and end up with:

A: {1 2}

But if I use A.removeAll(B) I will end up with only the value 2 since all the duplicate instances of value 1 will be removed from list A. My solution up until now was to use an Iterator over all elements of A and then all elements of B and if I find a similar value then remove it from both lists until list B is empty.

Is there a better way of doing it?

Upvotes: 0

Views: 200

Answers (1)

davidxxx
davidxxx

Reputation: 131396

You don't need to use a nested loop.
Loop on the b that contains the value to remove in a and use List.remove(Object) instead of List.removeAll(Collection).
It will remove the first element equals to the parameter and not all of them.

List<Integer> a = new ArrayList<>(Arrays.asList(1, 3, 1, 2));
List<Integer> b = Arrays.asList(1, 3);

for (Integer currentInt : b) {
    a.remove(currentInt);
}

System.out.println(a);

Output :

[1, 2]

Upvotes: 5

Related Questions