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.
Parameter | Optional/Required | Description |
---|---|---|
combine | required | a function that combines two elements of the collection |
List.reduce() returns value of type E
.
In this example,
numbers
containing the integers [1, 2, 3, 4, 5]
.reduce()
method to iteratively sum all elements of the list.reduce()
method takes a function that adds two integers together as its argument.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int sum = numbers.reduce((value, element) => value + element); // Output: 15
print(sum);
}
15
In this example,
characters
containing the characters ['a', 'b', 'c']
.reduce()
method to iteratively concatenate all characters of the list into a single string.reduce()
method takes a function that concatenates two strings together as its argument.'abc'
.void main() {
List<String> characters = ['a', 'b', 'c'];
String concatenated = characters.reduce((value, element) => value + element); // Output: 'abc'
print(concatenated);
}
abc
In this example,
words
containing the strings ['Lorem', 'ipsum', 'dolor', 'sit', 'amet']
.reduce()
method to iteratively concatenate all words of the list into a single string with spaces in between.reduce()
method takes a function that concatenates two strings together as its argument.'Lorem ipsum dolor sit amet'
.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);
}
Lorem ipsum dolor sit amet
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.