Algorithm


  1. Input:

    • Receive two sets as input (Set A and Set B).
  2. Initialize Result Set:

    • Create an empty set to store the intersection result (let's call it intersectionSet).
  3. Iterate Through Elements:

    • Iterate through each element in Set A.
    • For each element, check if it is present in Set B.
  4. Add to Result Set:

    • If an element is present in both Set A and Set B, add it to the intersectionSet.
  5. Output:

    • The intersectionSet now contains the intersection of Set A and Set B.

 

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

x
+
cmd
Prime Numbers: [2, 3]
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

x
+
cmd
Backend Languages: [Java, JavaScript]
Frontend Languages: [JavaScript, CSS]
Common Languages: [JavaScript]
Advertisements

Demonstration


Java Programing Example to Calculate the intersection of two sets-DevsEnv