Dart Set fold()
Syntax & Examples


Set.fold() method

The `fold` method in Dart reduces a collection to a single value by iteratively combining each element of the collection with an existing value.


Syntax of Set.fold()

The syntax of Set.fold() method is:

 T fold<T>(T initialValue, T combine(T previousValue, E element)) 

This fold() method of Set reduces a collection to a single value by iteratively combining each element of the collection with an existing value

Parameters

ParameterOptional/RequiredDescription
initialValuerequiredThe initial value to start the folding operation with.
combinerequiredA function that takes the previous value and the current element as input and returns the result of combining them.

Return Type

Set.fold() returns value of type T.



✐ Examples

1 Calculate sum of integers

In this example,

  1. We create a Set set containing integers.
  2. We use the fold() method with an initial value of 0 and a combining function that adds each element to the previous sum.
  3. We print the sum of the set elements to standard output.

Dart Program

void main() {
  Set<int> set = {1, 2, 3, 4, 5};
  int sum = set.fold(0, (previousValue, element) => previousValue + element);
  print('Sum of set elements: $sum');
}

Output

Sum of set elements: 15

2 Concatenate strings

In this example,

  1. We create a Set set containing strings.
  2. We use the fold() method with an initial value of an empty string and a combining function that concatenates each string with the previous value.
  3. We print the concatenated string to standard output.

Dart Program

void main() {
  Set<String> set = {'apple', 'banana', 'orange'};
  String concatenated = set.fold('', (previousValue, element) => previousValue + ' ' + element);
  print('Concatenated string: $concatenated');
}

Output

Concatenated string:  apple banana orange

Summary

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