Dart Set intersection()
Syntax & Examples
Set.intersection() method
The `intersection` method in Dart returns a new Set containing elements that are present in both this set and another set.
Syntax of Set.intersection()
The syntax of Set.intersection() method is:
Set<E> intersection(Set<Object> other)
This intersection() method of Set returns a new set which is the intersection between this set and other.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
other | required | A Set of objects to compute the intersection with this Set. |
Return Type
Set.intersection() returns value of type Set<E>
.
✐ Examples
1 Intersection of two integer sets
In this example,
- We create two Sets,
set1
andset2
, containing integers. - We use the
intersection()
method to compute the intersection ofset1
andset2
. - We print the resulting Set to standard output.
Dart Program
void main() {
Set<int> set1 = {1, 2, 3, 4};
Set<int> set2 = {3, 4, 5, 6};
Set<int> intersectedSet = set1.intersection(set2);
print('Intersection of set1 and set2: $intersectedSet');
}
Output
Intersection of set1 and set2: {3, 4}
2 Intersection of two string sets
In this example,
- We create two Sets,
set1
andset2
, containing strings. - We use the
intersection()
method to compute the intersection ofset1
andset2
. - We print the resulting Set to standard output.
Dart Program
void main() {
Set<String> set1 = {'apple', 'banana', 'orange'};
Set<String> set2 = {'banana', 'orange', 'grape'};
Set<String> intersectedSet = set1.intersection(set2);
print('Intersection of set1 and set2: $intersectedSet');
}
Output
Intersection of set1 and set2: {banana, orange}
Summary
In this Dart tutorial, we learned about intersection() method of Set: the syntax and few working examples with output and detailed explanation for each example.