Java Program to Find the Intersection Between Two Collection
Last Updated :
28 Jul, 2022
Collection means a set of different classes and interfaces are group together into a single unit that has similar functions are called collection and framework we know very that provides a predefined architecture to represents and manipulate collections in java. Here we will be discussing discuss out how to find the intersection between the two collections i.e Remove all the elements from the first collection if it is not available in the second collection.
In this article we will use two collection framework classes vector class and ArrayList class to find the intersection between the two collection.
Methods:
- Using ArrayList.contains() Method
- Using Vector.retainAll() method
Approach 1:
- Store the elements in the First collection and in the second collection (Array List).
- Now Iterate the First collection and checks whether the second collection contains elements of the first collection or not.
- If not contains remove the element from the first collection.
- Print the first collection.
Example:
Java
import java.io.*;
import java.util.*;
public class GFG {
static ArrayList<Integer>
RemoveElements(ArrayList<Integer> A,
ArrayList<Integer> B)
{
for ( int i = 0 ; i < A.size(); ++i) {
if (B.contains(A.get(i)) == false ) {
A.remove(i);
}
}
return A;
}
static void print(ArrayList<Integer> A)
{
for ( int element : A) {
System.out.print(element + " " );
}
}
public static void main(String[] args)
{
ArrayList<Integer> A = new ArrayList<>();
A.add( 1 );
A.add( 2 );
A.add( 3 );
A.add( 4 );
ArrayList<Integer> B = new ArrayList<>();
B.add( 1 );
B.add( 2 );
B.add( 3 );
ArrayList<Integer> UpdatedCollection
= RemoveElements(A, B);
print(A);
}
}
|
Time Complexity: O(n)
Space Complexity: O(n)
Approach 2: Using Vector.retainAll() method
- Store the elements in the First collection and in the second collection (Vector).
- Now use Vector.retainAll() method
- Print the first collection.
Example:
Java
import java.io.*;
import java.util.*;
public class GFG {
static Vector<Integer> RemoveElements(Vector<Integer> A,
Vector<Integer> B)
{
A.retainAll(B);
return A;
}
static void print(Vector<Integer> A)
{
for ( int element : A) {
System.out.print(element + " " );
}
}
public static void main(String[] args)
{
Vector<Integer> A = new Vector<>();
A.add( 1 );
A.add( 2 );
A.add( 3 );
A.add( 4 );
Vector<Integer> B = new Vector<>();
B.add( 1 );
B.add( 2 );
B.add( 3 );
Vector<Integer> UpdatedCollection
= RemoveElements(A, B);
print(A);
}
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...