Dart Programming – Collection Queue

  • Post author:
  • Post category:Dart
  • Post comments:2 Comments
Dart Programming Collection queue

In this guide, we will discuss Collection Queue in Dart Programming Language. A Queue is a collection that can be manipulated at both ends. Queues are useful when you want to build a first-in, first-out collection. Simply put, a queue inserts data from one end and deletes from another end. The values are removed / read in the order of their insertion.

Syntax: Creating a Queue

Identifier = new Queue()

The add() function can be used to insert values to the queue. This function inserts the value specified to the end of the queue. The following example illustrates the same.

Example

import 'dart:collection'; 
void main() { 
   Queue queue = new Queue(); 
   print("Default implementation ${queue.runtimeType}"); 
   queue.add(10); 
   queue.add(20); 
   queue.add(30); 
   queue.add(40); 
   
   for(var no in queue){ 
      print(no); 
   } 
}      

It should produce the following output −

Default implementation ListQueue
10 
20 
30 
40 

Adding Multiple Values to a Queue

The addAll() function enables adding multiple values to a queue, all at once. This function takes an iterable list of values.

Example

import 'dart:collection'; 
void main() { 
   Queue queue = new Queue(); 
   print("Default implementation ${queue.runtimeType}"); 
   queue.addAll([10,12,13,14]); 
   for(var no in queue){ 
      print(no); 
   } 
}

It should produce the following output −

Default implementation ListQueue 
10 
12 
13 
14 

Adding Value at the Beginning and End of a Queue

The addFirst() method adds the specified value to the beginning of the queue. This function is passed an object that represents the value to be added. The addLast() function adds the specified object to the end of the queue.

Example: addFirst()

The following example shows how you can add a value at the beginning of a Queue using the addFirst() method −

import 'dart:collection'; 
void main() { 
   Queue numQ = new Queue(); 
   numQ.addAll([100,200,300]); 
   print("Printing Q.. ${numQ}");
   numQ.addFirst(400); 
   print("Printing Q.. ${numQ}"); 
}   

It should produce the following output −

Printing Q.. {100, 200, 300} 
Printing Q.. {400, 100, 200, 300}

Example : addLast()

The following example shows how you can add a value at the beginning of a Queue using the addLast() method −

import 'dart:collection'; 
void main() { 
   Queue numQ = new Queue(); 
   numQ.addAll([100,200,300]); 
   print("Printing Q.. ${numQ}");  
   numQ.addLast(400); 
   print("Printing Q.. ${numQ}"); 
} 

It should produce the following output −

Printing Q.. {100, 200, 300} 
Printing Q.. {100, 200, 300, 400} 

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply