Dart List reduce()
Syntax & Examples
Syntax of List.reduce()
The syntax of List.reduce() method is:
E reduce(E combine(E value, E element)) This reduce() method of List reduces a collection to a single value by iteratively combining elements of the collection using the provided function.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
combine | required | a function that combines two elements of the collection |
Return Type
List.reduce() returns value of type E.
✐ Examples
1 Sum of numbers
In this example,
- We create a list named
numberscontaining the integers[1, 2, 3, 4, 5]. - We then use the
reduce()method to iteratively sum all elements of the list. - The
reduce()method takes a function that adds two integers together as its argument. - As a result, the sum of all numbers in the list is computed.
- We print the sum to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int sum = numbers.reduce((value, element) => value + element); // Output: 15
print(sum);
}Output
15
2 Concatenation of characters
In this example,
- We create a list named
characterscontaining the characters['a', 'b', 'c']. - We then use the
reduce()method to iteratively concatenate all characters of the list into a single string. - The
reduce()method takes a function that concatenates two strings together as its argument. - As a result, the characters are concatenated into the string
'abc'. - We print the concatenated string to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c'];
String concatenated = characters.reduce((value, element) => value + element); // Output: 'abc'
print(concatenated);
}Output
abc
3 Concatenation of words
In this example,
- We create a list named
wordscontaining the strings['Lorem', 'ipsum', 'dolor', 'sit', 'amet']. - We then use the
reduce()method to iteratively concatenate all words of the list into a single string with spaces in between. - The
reduce()method takes a function that concatenates two strings together as its argument. - As a result, the words are concatenated into the string
'Lorem ipsum dolor sit amet'. - We print the concatenated string to standard output.
Dart Program
void main() {
List<String> words = ['Lorem', 'ipsum', 'dolor', 'sit', 'amet'];
String concatenated = words.reduce((value, element) => value + ' ' + element); // Output: 'Lorem ipsum dolor sit amet'
print(concatenated);
}Output
Lorem ipsum dolor sit amet
Summary
In this Dart tutorial, we learned about reduce() method of List: the syntax and few working examples with output and detailed explanation for each example.