How to iterate over a queue in Dart
Overview
Dart allows users to manipulate data in the form of a queue.
A queue is a collection of objects. When you want to create a first-in, first-out data collection, queues come in handy.
The forEach loop
The forEach loop is used to iterate over a queue.
When using a
queuein a Dart program, you must import thedart: collectionmodule.
Syntax
queue_name.forEach((value))
queue_nameis the name of the queue.
Parameter and return
The forEach loop requires a value to perform its iteration and returns all values present in the queue.
Code
import 'dart:collection';void main() {// Creating a QueueQueue<String> fruits = Queue<String>();// Adding elements to the queuefruits.add('Mango');fruits.add('Pawpaw');fruits.addFirst('Apple');fruits.addLast('Pineapple');// Printing each element using forEachfruits.forEach((value)=> print(value));}
Explanation
-
In the code above, we import the
dart:collectionlibrary to utilize theQueueclass, then create aQueuenamedfruits. -
Next, we use the methods
add(),addFirst(), andaddLast()to add elements to the queue.-
The
queue_name.add(element)method is used to add the element in the queue. -
The
queue_name.addFirst(element)method inserts the element from the front inside the queue. -
The
queue_name.addLast(element)method adds the element from back in the queue.
-
-
Finally, each element in the queue is printed out using the
forEachloop.