Dart Set forEach()
Syntax & Examples
Set.forEach() method
The `forEach` method in Dart applies the provided function to each element of the set in iteration order.
Syntax of Set.forEach()
The syntax of Set.forEach() method is:
void forEach(void f(E element))
This forEach() method of Set applies the function f to each element of this collection in iteration order.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
f | required | The function to apply to each element of the set. |
Return Type
Set.forEach() returns value of type void
.
✐ Examples
1 Iterate over integers in the set
In this example,
- We create a Set
set
containing integers. - We use the
forEach()
method with a function that prints each element to standard output. - The elements are printed in the order they appear in the set.
Dart Program
void main() {
Set<int> set = {1, 2, 3, 4, 5};
set.forEach((element) => print('Element: $element'));
}
Output
Element: 1 Element: 2 Element: 3 Element: 4 Element: 5
2 Iterate over strings in the set
In this example,
- We create a Set
set
containing strings. - We use the
forEach()
method with a function that prints the length of each string to standard output. - The lengths of the strings are printed in the order they appear in the set.
Dart Program
void main() {
Set<String> set = {'apple', 'banana', 'orange'};
set.forEach((element) => print('Length of $element: ${element.length}'));
}
Output
Length of apple: 5 Length of banana: 6 Length of orange: 6
Summary
In this Dart tutorial, we learned about forEach() method of Set: the syntax and few working examples with output and detailed explanation for each example.