Dart Queue reduce function:
The reduce function will reduce one queue to a single value, it takes one combine function and it combines all elements to a single value. In this post, we will learn how reduce function works with different examples.
Syntax of the reduce function:
The syntax of the reduce function is:
reduce(E combine(E value, E element)) → E
It takes one function combine and with the help of this function, it will reduce the queue elements to a single value. It is a method defined for dart iterable. It starts with the first element and uses the combine function to combine all other values to reduce it to a single value. If the queue has only one element, it will return that element.
Example of the reduce function to find the sum of all values:
The following program uses the reduce method to find the sum of all digits of the given queue:
import 'dart:collection';
void main() {
var q = Queue.of([1, 2, 3, 4, 5]);
print("Given queue: ${q}");
var sum = q.reduce((v, e)=> v + e);
print("Sum: ${sum}");
}
In this program, q is the given queue of numbers. The reduce function returns the sum of the two values passed as its parameters.
If you run this program, it will print:
Given queue: {1, 2, 3, 4, 5}
Modified queue: 15
As you can see here, it is printing the total sum of the digits of the queue.
Example of the reduce function with objects:
Let’s try the reduce function with a queue of objects:
import 'dart:collection';
class Item {
String? name;
int? price;
Item(String name, int price) {
this.name = name;
this.price = price;
}
}
void main() {
var q =
Queue.of([Item("Item-1", 100), Item("Item-2", 24), Item("Item-3", 55)]);
var result =
q.reduce((value, element) => Item("", value.price! + element.price!));
print("Sum of all prices: ${result.price}");
}
Here,
- Item is a class to hold the name and price of an item.
- We created one queue, q, of three different items with different prices.
- The combine function should return a Item object. It adds the price of both value and element objects and creates a new object.
- The reduced value is assigned to the result variable.
If you run this program, it will print:
Sum of all prices: 179
i.e. the final Item variable holds the sum of the prices of all the objects.
Refer:
You might also like:
- Dart program to get the first n elements from a list
- How to create a string from ASCII values in Dart
- Dart StringBuffer class explanation with examples
- 5 ways in Dart to print the multiplication table
- Introduction to Queue in Dart and its methods
- How to add and remove items from a Queue in Dart
- How to remove and retain items from Queue in Dart with condition