0

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?

2
  • What would be the result for B: {3 1}? Commented Jun 12, 2018 at 19:41
  • @BheshGurung Exactly the same, the order of the elements should not be important Commented Jun 12, 2018 at 19:50

1 Answer 1

5

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]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.