How to use the union() method of LinkedHashSet in Dart
Overview
The union() method returns a new set by combining all the elements of the current set with the Set passed as an argument.
Syntax
Set<E> union(Set<E> other)
Parameter
This method takes a Set to be combined with the current Set as an argument.
Return value
This method returns a new set with all the elements of the current Set and the Set that is passed as an argument.
Code
The code below demonstrates the use of the union() method :
import 'dart:collection';void main() {//create a new LinkedHashSet which can have int type elementsLinkedHashSet set1 = new LinkedHashSet<int>();// add three elements to the setset1.add(1);set1.add(2);set1.add(3);print('The set1 is $set1');//create another LinkedHashSetLinkedHashSet set2 = new LinkedHashSet<int>();// add three elements to the setset2.add(3);set2.add(4);set2.add(5);print('The set2 is $set2');var unionResult = set1.union(set2); // combine set1 and set2print('\nset1.union(set2) : $unionResult');}
Explanation
-
Line 1: We import the
collectionlibrary. -
Lines 4 to 9: We create a new
LinkedHashSetobject namedset1. We then use theadd()method to add three elements (1,2,3) to theset1object. -
Lines 13 to 17: We create another
LinkedHashSetobject namedset2. We then use theadd()method to add three elements (3,4,5) to theset2object. -
Line 20: We use the
union()method onset1withset2as an argument. This method returns a newSetcontaining all theset1andset2elements. The elements of the returned set are[1,2,3,4,5].