The intersection of two sets is the set containing only the elements common to both sets Write a java method that takes as parameters 2 sets and returns a LinkedHashSet containing the intersection of the two sets without changing the contents of the parameters
The Correct Answer and Explanation is:
Here’s a Java method that takes two sets as parameters and returns a LinkedHashSet containing their intersection:
javaCopyEditimport java.util.Set;
import java.util.LinkedHashSet;
public class SetIntersection {
public static <T> LinkedHashSet<T> intersection(Set<T> set1, Set<T> set2) {
// Create a LinkedHashSet to store the intersection of both sets
LinkedHashSet<T> result = new LinkedHashSet<>();
// Iterate over the first set
for (T element : set1) {
// If the element is also in the second set, add it to the result
if (set2.contains(element)) {
result.add(element);
}
}
// Return the result, which contains only the common elements
return result;
}
public static void main(String[] args) {
Set<Integer> set1 = Set.of(1, 2, 3, 4, 5);
Set<Integer> set2 = Set.of(4, 5, 6, 7, 8);
// Calling the intersection method
LinkedHashSet<Integer> result = intersection(set1, set2);
// Printing the result
System.out.println("Intersection: " + result); // Output: [4, 5]
}
}
Explanation:
- Method Declaration:
The methodintersectiontakes two sets of typeT(generic type) as parameters. It returns aLinkedHashSet<T>, which preserves the order of elements from the first set while containing only those that are common to both sets. - LinkedHashSet:
ALinkedHashSetis used to store the result because it maintains the insertion order while ensuring uniqueness (i.e., no duplicates). - For-Each Loop:
The method iterates over the elements inset1. For each element, it checks if that element exists inset2using thecontains()method. - Adding to Result:
If an element is found in both sets, it is added to the result set (LinkedHashSet). - Return the Result:
The method returns the intersection set, containing only the common elements betweenset1andset2. - Main Method:
Themainmethod demonstrates the functionality by creating two sets, calling theintersection()method, and printing the result.
Why This Works:
- The
contains()method checks if each element ofset1is inset2, ensuring only common elements are added. LinkedHashSetis ideal here because it preserves insertion order, which is useful when you want to maintain the sequence of elements from the original sets.- This method works with any type of
Set(not justLinkedHashSet) because it uses the generic typeT. This allows it to be reusable for any set type (likeHashSet,TreeSet, etc.).
Efficiency:
- Time Complexity: The method runs in O(n * m) time, where
nis the size ofset1andmis the size ofset2, since thecontains()method of a set generally runs in O(1) average time.
