Dart – Reduce Elements of Set

To reduce elements of a Set to a single value, call reduce() method and pass the combine function as argument. combine is a function with two parameters, where the first parameter is used for accumulation/aggregation and the second parameter is each element from the Set.

Syntax

The syntax to call reduce() method on Set mySet with combine passed as argument is

mySet.reduce(combine)
ADVERTISEMENT

Examples

In the following program, we take a Set mySet, with some numbers, and reduce these numbers to their sum.

main.dart

int sum(int s, int e) {
  return s + e;
}

void main() {
  Set<int> mySet = {1, 3, 6, 10, 13, 15, 20};
  var result = mySet.reduce(sum);
  print('Result : $result');
}

Output

Result : 68

Now, let us take the same Set as in the above example, but reduce the elements to their product.

main.dart

int product(int s, int e) {
  return s * e;
}

void main() {
  Set<int> mySet = {1, 3, 6, 10, 13, 15, 20};
  var result = mySet.reduce(product);
  print('Result : $result');
}

Output

Result : 702000

Conclusion

In this Dart Tutorial, we learned how to reduce the elements of a Set to a single value, with examples.