Considering the code below and the fact that the 4 HashSet
s are populated elsewhere.
My aim is to contain all element(s) that are common in all 4 HashSets.
My question is that first of all, am I doing it right? Secondly, if I'm doing it right, is there a better way to do it? If not, then what solution do I have for this problem?
static Set<String> one=new HashSet<>();
static Set<String> two=new HashSet<>();
static Set<String> three=new HashSet<>();
static Set<String> four=new HashSet<>();
private static void createIntersectionQrels() {
ArrayList<String> temp = new ArrayList<>();
Set<String> interQrels = new HashSet<>();
temp.addAll(one);
one.retainAll(two);
interQrels.addAll(one);
one.addAll(temp);
one.retainAll(three);
interQrels.addAll(one);
one.addAll(temp);
one.retainAll(four);
interQrels.addAll(one);
one.addAll(temp);
interQrels.retainAll(two);
interQrels.retainAll(three);
interQrels.retainAll(four);
}
To understand this example, you should have the knowledge of the following Java programming topics: In the above example, we have created two sets named primeNumbers and evenNumbers. We have implemented the set using the HashSet class. Notice the line, Here, we have used the retainAll () method to get the intersection of two sets.
HashSet.IntersectWith (IEnumerable) Method is used to modify the current HashSet object to contain only elements that are present in that object and in the specified collection.
1 Definition and Usage. The intersection () method returns a set that contains the similarity between two or more sets. ... 2 Syntax 3 Parameter Values. The other set to search for equal items in. You can compare as many sets you like. 4 More Examples
The intersection () method returns a set that contains the similarity between two or more sets. Meaning: The returned set contains only items that exist in both sets, or in all sets if the comparison is done with more than two sets.
I think you can simply can call retainAll()
on the first set, using the second, third, and fourth sets as parameters:
private static Set<String> getIntersectionSet() {
// create a deep copy of one (in case you don't wish to modify it)
Set<String> interQrels = new HashSet<>(one);
interQrels.retainAll(two); // intersection with two (and one)
interQrels.retainAll(three); // intersection with three (and two, one)
interQrels.retainAll(four); // intersection four (and three, two, one)
return interQrels;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With