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