How to use the intersection() method of LinkedHashSet in Dart
Overview
The intersection() method gets the common elements of two Set objects.
This method finds the elements present in both sets, creates them as a new set, and returns them.
Syntax
Set<E> intersection(Set<E> other)
Argument
This method takes a Set object as an argument.
Return value
A new Set containing common elements between two Set objects is returned.
Code
The code demonstrates the use of the intersection() 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 set1set1.add(1);set1.add(2);set1.add(3);print('The set1 is $set1');//create another LinkedHashSet which can have int type elementsLinkedHashSet set2 = new LinkedHashSet<int>();// add three elements to the setset2.add(2);set2.add(3);set2.add(4);print('The set2 is $set2');// the common elements on set1 and set2 isSet<int> commonElements = set1.intersection(set2);print('The common elements is $commonElements');}
Code explanation
-
Line 1: We import the
collectionlibrary. -
Line 4: We create a new
LinkedHashSetobject namedset1. -
Lines 7-9: We add three new elements to
set1. Now,set1is {1,2,3}. -
Line 13: We create a new
LinkedHashSetobject namedset2. -
Lines 16-18: We add three new elements to the
set2. Now,set2is {2,3,4}. -
Line 23: We use the
intersection()method to get the common elements betweenset1andset2. In our case, the common elements between the two sets are2and3. Hence, a newSetcontaining elements 2 and 3 will be returned,{2,3}.