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.
forEach
loopThe forEach
loop is used to iterate over a queue
.
When using a
queue
in a Dart program, you must import thedart: collection
module.
queue_name.forEach((value))
queue_name
is the name of the queue.
The forEach
loop requires a value to perform its iteration and returns all values present in the queue.
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));}
In the code above, we import the dart:collection
library to utilize the Queue
class, then create a Queue
named fruits
.
Next, we use the methods add()
, addFirst()
, and addLast()
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 forEach
loop.