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

ParameterOptional/RequiredDescription
elementsrequiredAn 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,

  1. We create a Set numSet with values {1, 2, 3, 4}.
  2. We create a List elementsToRetain containing elements [2, 3] to retain in numSet.
  3. We use the retainAll() method to retain only the elements from numSet that are in elementsToRetain.
  4. 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,

  1. We create a Set charSet with values {'a', 'b', 'c', 'd'}.
  2. We create a List elementsToRetain containing elements ['b', 'd'] to retain in charSet.
  3. We use the retainAll() method to retain only the elements from charSet that are in elementsToRetain.
  4. 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,

  1. We create a Set wordSet with values {'apple', 'banana', 'cherry', 'orange'}.
  2. We create a List elementsToRetain containing elements ['banana', 'orange'] to retain in wordSet.
  3. We use the retainAll() method to retain only the elements from wordSet that are in elementsToRetain.
  4. 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.