Dart Set iterator
Syntax & Examples


Set.iterator property

The `iterator` property in Dart provides an iterator that iterates over the elements of this set.


Syntax of Set.iterator

The syntax of Set.iterator property is:

 Iterator<E> iterator 

This iterator property of Set provides an iterator that iterates over the elements of this set.

Return Type

Set.iterator returns value of type Iterator<E>.



✐ Examples

1 Iterating over a set of numbers

In this example,

  1. We create a set numSet containing integer numbers.
  2. We obtain an iterator using the iterator property.
  3. We iterate over the set using a while loop, printing each element.

Dart Program

void main() {
  Set<int> numSet = {1, 2, 3, 4, 5};
  Iterator<int> iter = numSet.iterator;
  while (iter.moveNext()) {
    print(iter.current);
  }
}

Output

1
2
3
4
5

2 Iterating over a set of characters

In this example,

  1. We create a set charSet containing character elements.
  2. We obtain an iterator using the iterator property.
  3. We iterate over the set using a while loop, printing each character.

Dart Program

void main() {
  Set<String> charSet = {'a', 'b', 'c', 'd', 'e'};
  Iterator<String> iter = charSet.iterator;
  while (iter.moveNext()) {
    print(iter.current);
  }
}

Output

a
b
c
d
e

3 Iterating over a set of strings

In this example,

  1. We create a set stringSet containing string elements.
  2. We obtain an iterator using the iterator property.
  3. We iterate over the set using a while loop, printing each string.

Dart Program

void main() {
  Set<String> stringSet = {'apple', 'banana', 'cherry', 'date', 'elderberry'};
  Iterator<String> iter = stringSet.iterator;
  while (iter.moveNext()) {
    print(iter.current);
  }
}

Output

apple
banana
cherry
date
elderberry

Summary

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