Dart List fold()
Syntax & Examples
Syntax of List.fold()
The syntax of List.fold() method is:
T fold<T>(T initialValue, T combine(T previousValue, E element))
This fold() method of List reduces a collection to a single value by iteratively combining each element of the collection with an existing value
Parameters
Parameter | Optional/Required | Description |
---|---|---|
initialValue | required | the initial value to start the accumulation |
combine | required | a function that combines the previous value and the current element to produce a new value |
Return Type
List.fold() returns value of type T
.
✐ Examples
1 Sum of numbers
In this example,
- We create a list named
numbers
containing the numbers1, 2, 3, 4, 5
. - We then use the
fold()
method starting with an initial value of0
. - The provided function accumulates the sum of all elements.
- The final sum is printed to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int sum = numbers.fold(0, (previous, current) => previous + current);
print('Sum of numbers: $sum'); // Output: Sum of numbers: 15
}
Output
Sum of numbers: 15
2 Concatenated characters
In this example,
- We create a list named
characters
containing the characters'a', 'b', 'c', 'd', 'e'
. - We then use the
fold()
method starting with an initial value of an empty string''
. - The provided function concatenates all characters into a single string.
- The concatenated string is printed to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c', 'd', 'e'];
String concatenated = characters.fold('', (previous, current) => previous + current);
print('Concatenated characters: $concatenated'); // Output: Concatenated characters: abcde
}
Output
Concatenated characters: abcde
3 Total length of strings
In this example,
- We create a list named
fruits
containing the strings'apple', 'banana', 'cherry'
. - We then use the
fold()
method starting with an initial value of0
. - The provided function accumulates the total length of all strings.
- The total length is printed to standard output.
Dart Program
void main() {
List<String> fruits = ['apple', 'banana', 'cherry'];
int totalLength = fruits.fold<int>(0, (previous, current) => previous + current.length);
print('Total length of strings: $totalLength');
}
Output
Total length of strings: 17
Summary
In this Dart tutorial, we learned about fold() method of List: the syntax and few working examples with output and detailed explanation for each example.