Tal Barda Tal Barda - 4 months ago 8
Java Question

How can I remove object in one array from another array?

Let's say I have these lists:

List<int> numbersA=new ArrayList<int>();
List<int> numbersB=new ArrayList<int>();


"Numbers A" is [1,3,4,7,5,2] (There are no duplicate numbers)
and "Numbers B" is: [13,32,533,3,4,2]

So the method will remove "Numbers A" from "Numbers B",and "Numbers B" will be:
[13,32,533]

(Iv'e noticed later that int List won't compile... It's just for the example)

Answer

Use the method RemoveAll, here the doc

Example:

public static void main(String[] args) {
List<Integer> numbersA = new ArrayList<>();
List<Integer> numbersB = new ArrayList<>();
numbersA.addAll(Arrays.asList(new Integer[] { 1, 3, 4, 7, 5, 2 }));
numbersB.addAll(Arrays.asList(new Integer[] { 13, 32, 533, 3, 4, 2 }));
System.out.println("A: " + numbersA);
System.out.println("B: " + numbersB);

numbersB.removeAll(numbersA);
System.out.println("B cleared: " + numbersB);
}

this will print

A: [1, 3, 4, 7, 5, 2]

B: [13, 32, 533, 3, 4, 2]

B cleared: [13, 32, 533]

Comments