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
numSet
with values {1, 2, 3, 4}. - We create a List
elementsToRetain
containing elements [2, 3] to retain innumSet
. - We use the
retainAll()
method to retain only the elements fromnumSet
that are inelementsToRetain
. - We print the updated
numSet
after 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
charSet
with values {'a', 'b', 'c', 'd'}. - We create a List
elementsToRetain
containing elements ['b', 'd'] to retain incharSet
. - We use the
retainAll()
method to retain only the elements fromcharSet
that are inelementsToRetain
. - We print the updated
charSet
after 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
wordSet
with values {'apple', 'banana', 'cherry', 'orange'}. - We create a List
elementsToRetain
containing elements ['banana', 'orange'] to retain inwordSet
. - We use the
retainAll()
method to retain only the elements fromwordSet
that are inelementsToRetain
. - We print the updated
wordSet
after 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.