Dart Tutorials

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

ParameterOptional/RequiredDescription
combinerequireda 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,

  1. We create a list named numbers containing the integers [1, 2, 3, 4, 5].
  2. We then use the reduce() method to iteratively sum all elements of the list.
  3. The reduce() method takes a function that adds two integers together as its argument.
  4. As a result, the sum of all numbers in the list is computed.
  5. 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,

  1. We create a list named characters containing the characters ['a', 'b', 'c'].
  2. We then use the reduce() method to iteratively concatenate all characters of the list into a single string.
  3. The reduce() method takes a function that concatenates two strings together as its argument.
  4. As a result, the characters are concatenated into the string 'abc'.
  5. 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,

  1. We create a list named words containing the strings ['Lorem', 'ipsum', 'dolor', 'sit', 'amet'].
  2. We then use the reduce() method to iteratively concatenate all words of the list into a single string with spaces in between.
  3. The reduce() method takes a function that concatenates two strings together as its argument.
  4. As a result, the words are concatenated into the string 'Lorem ipsum dolor sit amet'.
  5. 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.