Dart Set addAll()
Syntax & Examples
Syntax of Set.addAll()
The syntax of Set.addAll() method is:
void addAll(Iterable<E> elements) This addAll() method of Set adds all elements to this Set.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
elements | required | An Iterable containing elements to add to the Set. |
Return Type
Set.addAll() returns value of type void.
✐ Examples
1 Adding numbers to a Set
In this example,
- We create a Set
numSetwith initial values {1, 2, 3}. - We create a List
numbersToAddcontaining elements [4, 5, 6] to add tonumSet. - We use the
addAll()method to add all elements fromnumbersToAddtonumSet. - We print the updated
numSetafter addition.
Dart Program
void main() {
Set<int> numSet = {1, 2, 3};
List<int> numbersToAdd = [4, 5, 6];
numSet.addAll(numbersToAdd);
print(numSet);
}Output
{1, 2, 3, 4, 5, 6}2 Adding characters to a Set
In this example,
- We create a Set
charSetwith initial values {'a', 'b', 'c'}. - We create a List
charsToAddcontaining elements ['d', 'e', 'f'] to add tocharSet. - We use the
addAll()method to add all elements fromcharsToAddtocharSet. - We print the updated
charSetafter addition.
Dart Program
void main() {
Set<String> charSet = {'a', 'b', 'c'};
List<String> charsToAdd = ['d', 'e', 'f'];
charSet.addAll(charsToAdd);
print(charSet);
}Output
{a, b, c, d, e, f}3 Adding strings to a Set
In this example,
- We create a Set
wordSetwith initial values {'hello', 'world'}. - We create a List
wordsToAddcontaining elements ['open', 'source'] to add towordSet. - We use the
addAll()method to add all elements fromwordsToAddtowordSet. - We print the updated
wordSetafter addition.
Dart Program
void main() {
Set<String> wordSet = {'hello', 'world'};
List<String> wordsToAdd = ['open', 'source'];
wordSet.addAll(wordsToAdd);
print(wordSet);
}Output
{hello, world, open, source}Summary
In this Dart tutorial, we learned about addAll() method of Set: the syntax and few working examples with output and detailed explanation for each example.