Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove common values from two array lists

Tags:

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?

like image 609
Gautam Avatar asked Mar 22 '13 16:03

Gautam


People also ask

How do you remove common elements from two arrays in CPP?

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.

How do you find duplicates in ArrayList?

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.


1 Answers

Here is an algorithm that you could follow to accomplish the task:

  • Construct a union of the two arrays
  • Construct the intersection of the two arrays
  • Subtract the intersection from the union to get your result

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); } 
like image 167
Sergey Kalinichenko Avatar answered Nov 27 '22 08:11

Sergey Kalinichenko