public class RemoveCommonElements {
public static void main(String[] args) {
RemoveCommonElements app = new RemoveCommonElements();
app.commonRemove();
}
private void commonRemove() {
int[] arr1 = { 1, 4, 6, 7, 8 };
int[] arr2 = { 2, 4, 5, 9, 0 };
for (int e : arr1) {
if (contains(arr2, e)) {
remove(arr1, e);
remove(arr2, e);
}
}
System.out.print(arr1);
System.out.print(arr2);
}
private boolean contains(int[] arr, int e) {
for (int i : arr) {
if (i == e) {
return true;
}
}
return false;
}
private int[] remove(int[] arr, int e) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == e) {
for (int j = i; j < arr.length-1; j++) {
arr[j] = arr[j + 1];
}
}
}
return arr;
}
}
######### RESULT ##########
1, 6, 7, 8, 8
2, 5, 9, 0 ,0
/**
* Get UNION list
* Get INTERSECTION LIST by retainAll //common elements
* Remove intersection from union
*/
private static void removeCommonElements() {
List list1 = Arrays.asList(1, 2, 3, 4, 5, 6);
List list2 = Arrays.asList(10, 2, 3, 40, 50, 60);
List union = new ArrayList(list1);
union.addAll(list2);
List intersection = new ArrayList<>(list1);
// only common elements
intersection.retainAll(list2);
union.removeAll(intersection);
System.out.println(union);
}
No comments:
Post a Comment