Algorithm
-
Input:
- Receive two sets as input (Set A and Set B).
-
Initialize Result Set:
- Create an empty set to store the intersection result (let's call it
intersectionSet
).
- Create an empty set to store the intersection result (let's call it
-
Iterate Through Elements:
- Iterate through each element in Set A.
- For each element, check if it is present in Set B.
-
Add to Result Set:
- If an element is present in both Set A and Set B, add it to the
intersectionSet
.
- If an element is present in both Set A and Set B, add it to the
-
Output:
- The
intersectionSet
now contains the intersection of Set A and Set B.
- The
Code Examples
#1 Code Example- Calculate the intersection of two sets
Code -
Java Programming
import java.util.HashSet;
import java.util.Set;
class Main {
public static void main(String[] args) {
// create first set
Set < Integer> primeNumbers = new HashSet<>();
primeNumbers.add(2);
primeNumbers.add(3);
System.out.println("Prime Numbers: " + primeNumbers);
// create second set
Set < Integer> evenNumbers = new HashSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("Even Numbers: " + evenNumbers);
// Intersection of two sets
evenNumbers.retainAll(primeNumbers);
System.out.println("Intersection: " + evenNumbers);
}
}
Copy The Code &
Try With Live Editor
Output
Prime Numbers: [2, 3]
Even Numbers: [2, 4]
Intersection: [2]
Even Numbers: [2, 4]
Intersection: [2]
#2 Code Example- Get union of two sets using Guava Library
Code -
Java Programming
import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.Sets;
class Main {
public static void main(String[] args) {
// create the first set
Set < String> backend = new HashSet<>();
backend.add("Java");
backend.add("JavaScript");
System.out.println("Backend Languages: " + backend);
// create second set
Set < String> frontend = new HashSet<>();
frontend.add("JavaScript");
frontend.add("CSS");
System.out.println("Frontend Languages: " + frontend);
Set < String> intersect = Sets.intersection(backend, frontend);
System.out.println("Common Languages: " + intersect);
}
}
Copy The Code &
Try With Live Editor
Output
Backend Languages: [Java, JavaScript]
Frontend Languages: [JavaScript, CSS]
Common Languages: [JavaScript]
Frontend Languages: [JavaScript, CSS]
Common Languages: [JavaScript]
Demonstration
Java Programing Example to Calculate the intersection of two sets-DevsEnv