Dart Set removeAll()
Syntax & Examples


Syntax of Set.removeAll()

The syntax of Set.removeAll() method is:

 void removeAll(Iterable<Object> elements) 

This removeAll() method of Set removes each element of elements from this set.

Parameters

ParameterOptional/RequiredDescription
elementsrequiredAn Iterable containing elements to be removed from the Set.

Return Type

Set.removeAll() returns value of type void.



✐ Examples

1 Removing elements from Set of numbers

In this example,

  1. We create a Set numSet with values {1, 2, 3, 4}.
  2. We create a List elementsToRemove containing elements [2, 3] to be removed from numSet.
  3. We use the removeAll() method to remove all elements from numSet that are in elementsToRemove.
  4. We print the updated numSet after removal.

Dart Program

void main() {
  Set<int> numSet = {1, 2, 3, 4};
  List<int> elementsToRemove = [2, 3];
  numSet.removeAll(elementsToRemove);
  print(numSet);
}

Output

{1, 4}

2 Removing elements from Set of characters

In this example,

  1. We create a Set charSet with values {'a', 'b', 'c', 'd'}.
  2. We create a List elementsToRemove containing elements ['b', 'd'] to be removed from charSet.
  3. We use the removeAll() method to remove all elements from charSet that are in elementsToRemove.
  4. We print the updated charSet after removal.

Dart Program

void main() {
  Set<String> charSet = {'a', 'b', 'c', 'd'};
  List<String> elementsToRemove = ['b', 'd'];
  charSet.removeAll(elementsToRemove);
  print(charSet);
}

Output

{a, c}

3 Removing elements from Set of strings

In this example,

  1. We create a Set wordSet with values {'apple', 'banana', 'cherry', 'orange'}.
  2. We create a List elementsToRemove containing elements ['banana', 'orange'] to be removed from wordSet.
  3. We use the removeAll() method to remove all elements from wordSet that are in elementsToRemove.
  4. We print the updated wordSet after removal.

Dart Program

void main() {
  Set<String> wordSet = {'apple', 'banana', 'cherry', 'orange'};
  List<String> elementsToRemove = ['banana', 'orange'];
  wordSet.removeAll(elementsToRemove);
  print(wordSet);
}

Output

{apple, cherry}

Summary

In this Dart tutorial, we learned about removeAll() method of Set: the syntax and few working examples with output and detailed explanation for each example.