Dart Set retainAll()
Syntax & Examples
Syntax of Set.retainAll()
The syntax of Set.retainAll() method is:
void retainAll(Iterable<Object> elements) This retainAll() method of Set removes all elements of this set that are not elements in elements.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
elements | required | An Iterable containing elements to retain in the Set. |
Return Type
Set.retainAll() returns value of type void.
✐ Examples
1 Retaining elements in Set of numbers
In this example,
- We create a Set
numSetwith values {1, 2, 3, 4}. - We create a List
elementsToRetaincontaining elements [2, 3] to retain innumSet. - We use the
retainAll()method to retain only the elements fromnumSetthat are inelementsToRetain. - We print the updated
numSetafter retention.
Dart Program
void main() {
Set<int> numSet = {1, 2, 3, 4};
List<int> elementsToRetain = [2, 3];
numSet.retainAll(elementsToRetain);
print(numSet);
}Output
{2, 3}2 Retaining elements in Set of characters
In this example,
- We create a Set
charSetwith values {'a', 'b', 'c', 'd'}. - We create a List
elementsToRetaincontaining elements ['b', 'd'] to retain incharSet. - We use the
retainAll()method to retain only the elements fromcharSetthat are inelementsToRetain. - We print the updated
charSetafter retention.
Dart Program
void main() {
Set<String> charSet = {'a', 'b', 'c', 'd'};
List<String> elementsToRetain = ['b', 'd'];
charSet.retainAll(elementsToRetain);
print(charSet);
}Output
{b, d}3 Retaining elements in Set of strings
In this example,
- We create a Set
wordSetwith values {'apple', 'banana', 'cherry', 'orange'}. - We create a List
elementsToRetaincontaining elements ['banana', 'orange'] to retain inwordSet. - We use the
retainAll()method to retain only the elements fromwordSetthat are inelementsToRetain. - We print the updated
wordSetafter retention.
Dart Program
void main() {
Set<String> wordSet = {'apple', 'banana', 'cherry', 'orange'};
List<String> elementsToRetain = ['banana', 'orange'];
wordSet.retainAll(elementsToRetain);
print(wordSet);
}Output
{banana, orange}Summary
In this Dart tutorial, we learned about retainAll() method of Set: the syntax and few working examples with output and detailed explanation for each example.