Dart Set reduce()
Syntax & Examples


Set.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 Set.reduce()

The syntax of Set.reduce() method is:

 E reduce(E combine(E value E element)) 

This reduce() method of Set reduces a collection to a single value by iteratively combining elements of the collection using the provided function.

Parameters

ParameterOptional/RequiredDescription
combinerequiredA function that takes two elements and combines them into one.

Return Type

Set.reduce() returns value of type E.



✐ Examples

1 Reducing a set of numbers

In this example,

  1. We create a Set numbers with values {1, 2, 3, 4, 5}.
  2. We use the reduce() method with a combining function that adds the elements together.
  3. We print the result, which is the sum of all numbers in the set.

Dart Program

void main() {
  Set<int> numbers = {1, 2, 3, 4, 5};
  int sum = numbers.reduce((value, element) => value + element);
  print(sum);
}

Output

15

2 Reducing a set of strings

In this example,

  1. We create a Set words with values {'apple', 'banana', 'cherry'}.
  2. We use the reduce() method with a combining function that concatenates the strings with spaces.
  3. We print the result, which is the combined string of all words in the set.

Dart Program

void main() {
  Set<String> words = {'apple', 'banana', 'cherry'};
  String combined = words.reduce((value, element) => value + ' ' + element);
  print(combined);
}

Output

apple banana cherry

Summary

In this Dart tutorial, we learned about reduce() method of Set: the syntax and few working examples with output and detailed explanation for each example.