How can we remove common values from two ArrayLists?
Let’s consider I have two Arraylist as shown below:
ArrayList1 = [1,2,3,4] ArrayList1 = [2,3,4,6,7]
I would like to have result as:
ArrayListFinal = [1,6,7]
How can I do it?
Given that, if you are allowed to sort both sequences, you can use std::set_intersection to first find the common elements. Then use std::remove_if on both vectors using the generated set of common elements.
One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.
Here is an algorithm that you could follow to accomplish the task:
Java collections support addAll
, removeAll
, and retainAll
. Use addAll
to construct unions, retainAll
for constructing intersections, and removeAll
for subtraction, like this:
// Make the two lists List<Integer> list1 = Arrays.asList(1, 2, 3, 4); List<Integer> list2 = Arrays.asList(2, 3, 4, 6, 7); // Prepare a union List<Integer> union = new ArrayList<Integer>(list1); union.addAll(list2); // Prepare an intersection List<Integer> intersection = new ArrayList<Integer>(list1); intersection.retainAll(list2); // Subtract the intersection from the union union.removeAll(intersection); // Print the result for (Integer n : union) { System.out.println(n); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With