How to use the retainAll() method of LinkedHashSet in Dart
The retainAll() method removes all the elements of the LinkedHashSet object not present in the provided collection. The method leaves the elements which are present in both of the collections.
Syntax
void retainAll(Iterable<Object?> elements);
This method takes an iterable/collection object to be retained in the LinkedHashSet as a parameter.
Code
import 'dart:collection';void main() {//create a new LinkedHashSet which can have int type elementsLinkedHashSet set = new LinkedHashSet<int>();// add three elements to the setset.add(1);set.add(2);set.add(3);print('The set is $set');// create a queueListQueue queue = new ListQueue();// add 4 elements to the queuequeue.add(1);queue.add(4);print('The queue is $queue');set.retainAll(queue);print('After calling set.retainAll(queue)');print('The set is $set');}
Explanation
In the code above:
-
Line 1: We import the
collectionlibrary. -
Lines 4 to 9: We create a new
LinkedHashSetobject namedset. We then use theadd()method to add three elements (1,2,3) to thesetobject. -
Lines 13 to 17: We create a new
ListQueueobject namedqueue. Then, we use theadd()method to add two elements (1,4) to thequeueobject. -
Line 20: We use the
retainAllmethod to only retain the elements present in thequeue. In our case, the elements of thequeueand the set are as follows:
Set -- 1 , 2 , 3Queue -- 1, 4
The retainAll method:
- Checks if element
1of thesetis present in thequeue. Thequeuecontains1, so1is retained in theset. - Checks if element
2of thesetis present in thequeue. Thequeuedoesn’t contain2, so2is removed from the set. - Checks if element
3of thesetis present in thequeue. Thequeuedoesn’t contain3, so3is removed from the set.
The resulting set is [1].