Dart Runes reduce()
Syntax & Examples
Runes.reduce() method
The `reduce` method in Dart reduces a collection to a single value by iteratively combining elements of the collection using the provided function.
Syntax of Runes.reduce()
The syntax of Runes.reduce() method is:
int reduce(int combine(int value int element))
This reduce() method of Runes 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 takes an integer value and an integer element, and returns the new combined value. |
Return Type
Runes.reduce() returns value of type int
.
✐ Examples
1 Reducing a list of numbers to calculate the sum
In this example,
- We create a list
numbers
containing integers. - We use the
reduce()
method with a function that adds each element to the accumulated value. - We print the final sum obtained by reducing the list.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int sum = numbers.reduce((value, element) => value + element);
print(sum);
}
Output
15
2 Reducing a list of strings to concatenate them
In this example,
- We create a list
words
containing strings. - We use the
reduce()
method with a function that concatenates each word to the accumulated value with a space. - We print the final concatenated string obtained by reducing the list.
Dart Program
void main() {
List<String> words = ['hello', 'world'];
String combined = words.reduce((value, word) => value + ' ' + word);
print(combined);
}
Output
hello world
3 Reducing a set of numbers to calculate the product
In this example,
- We create a set
uniqueNumbers
containing integers. - We use the
reduce()
method with a function that multiplies each element to the accumulated value. - We print the final product obtained by reducing the set.
Dart Program
void main() {
Set<int> uniqueNumbers = {1, 2, 3};
int product = uniqueNumbers.reduce((value, number) => value * number);
print(product);
}
Output
6
Summary
In this Dart tutorial, we learned about reduce() method of Runes: the syntax and few working examples with output and detailed explanation for each example.