The union()
method returns a new set by combining all the elements of the current set with the Set
passed as an argument.
Set<E> union(Set<E> other)
This method takes a Set
to be combined with the current Set
as an argument.
This method returns a new set with all the elements of the current Set
and the Set
that is passed as an argument.
The code below demonstrates the use of the union()
method :
import 'dart:collection'; void main() { //create a new LinkedHashSet which can have int type elements LinkedHashSet set1 = new LinkedHashSet<int>(); // add three elements to the set set1.add(1); set1.add(2); set1.add(3); print('The set1 is $set1'); //create another LinkedHashSet LinkedHashSet set2 = new LinkedHashSet<int>(); // add three elements to the set set2.add(3); set2.add(4); set2.add(5); print('The set2 is $set2'); var unionResult = set1.union(set2); // combine set1 and set2 print('\nset1.union(set2) : $unionResult'); }
Line 1: We import the collection
library.
Lines 4 to 9: We create a new LinkedHashSet
object named set1
. We then use the add()
method to add three elements (1,2,3
) to the set1
object.
Lines 13 to 17: We create another LinkedHashSet
object named set2
. We then use the add()
method to add three elements (3,4,5
) to the set2
object.
Line 20: We use the union()
method on set1
with set2
as an argument. This method returns a new Set
containing all the set1
and set2
elements. The elements of the returned set are [1,2,3,4,5]
.
RELATED TAGS
CONTRIBUTOR
View all Courses