Queue in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

A queue is a collection of objects. In Dart, we can do operations on both ends of the queue.

A queue can be created by making use of the Queue class this present inside the collection library of dart.

Example

Consider the example shown below −

 Live Demo

import 'dart:collection';

void main() {
   var queue = new Queue();
   print(queue);
}

In the above example, we imported the collection library so that Queue class can be used from it and then we create a Queue and store it in a variable named queue, and finally we print whatever is inside the queue variable.

Output

{}

We can add elements inside the queue by using different methods. Some of the most common methods are −

  • add() - adds object to the end of the Queue.

  • addFirst() - adds object to the starting of the Queue.

  • addLast() - adds object to the end of the Queue.

Example

Consider the example shown below −

 Live Demo

import 'dart:collection';

void main() {
   var queue = new Queue();
   queue.add('first');
   queue.add('second');
   queue.addFirst('third');
   print(queue);
}

Output

{third, first, second}

We can also print the element at a particular index of the list by making use of the ElementAt method.

Example

Consider the example shown below −

 Live Demo

import 'dart:collection';

void main() {
   var queue = new Queue();
   queue.add('first');
   queue.add('second');
   queue.addFirst('third');
   var element = queue.elementAt(2);
   print(element);
}

Output

second

Checking if Queue contains an Element

We can use the contains() method to check if the Queue contains the element we are looking for.

Example

Consider the example shown below −

 Live Demo

import 'dart:collection';

void main() {
   var queue = new Queue();
   queue.add('first');
   queue.add('second');
   queue.addFirst('third');
   queue.addLast('fourth');
   var isPresent = queue.contains('third');
   print("is fourth Present? ${isPresent}");
}

Output

is fourth Present? true

Iterating over a Queue

We can use forEach loop if we want to iterate over a queue.

Example

Consider the example shown below −

import 'dart:collection';

void main() {
   var queue = new Queue();
   queue.add('first');
   queue.add('second');
   queue.addFirst('third');
   queue.addLast('fourth');
   queue.forEach((value)=>{
      print(value)
   });
}

Output

third
first
second
fourth
raja
Published on 24-May-2021 11:46:16
Advertisements