Open In App

Dart - Collections

Last Updated : 11 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Collections are groups of objects that represent a particular element. The dart::collection library is used to implement the Collection in Dart. There are a variety of collections available in Dart.

Dart Collection

There are 5 Interfaces that we have in the Dart Collection, as mentioned below:

  • List
  • Queue
  • Set
  • Map
  • LinkedList

collection-in-dart-new

1. List Interface

The list is an ordered group of objects where each object is from one specific type. To define a list in Dart, specify the object type inside the angled brackets (<>).

Syntax:

List<String> fruits = ["Mango", "Apple", "Banana"]

Example: 

Here, we have defined a list and performed some common operations along with some basic, commonly used methods.

Dart
void main() {
      // creating a new empty List
      List geekList = [];
    
      // Adding an element to the geekList
      geekList.addAll([1, 2, 3, 4, 5, "Apple"]);
      print(geekList);
    
      // Looping over the list
      for (var i = 0; i < geekList.length; i++) {
            print("element $i is ${geekList[i]}");
      }
    
      // Removing an element from geekList by index
      geekList.removeAt(2);
    
      // Removing an element from geekList by object
      geekList.remove("Apple");
      print(geekList);
    
      // Return a reversed version of the list
      print(geekList.reversed);
    
      // Checks if the list is empty
      print(geekList.isEmpty);
    
      // Gives the first element of the list
      print(geekList.first);
    
      // Reassigning the geekList and creating the
      // elements using Iterable
      geekList = Iterable<int>.generate(10).toList();
      print(geekList);
}


Output:

[1, 2, 3, 4, 5, Apple]
element 0 is 1
element 1 is 2
element 2 is 3
element 3 is 4
element 4 is 5
element 5 is Apple
[1, 2, 4, 5]
(5, 4, 2, 1)
false
1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


Classes Associated with List Interface

Class

Description

UnmodifiableListView<E>

An unmodifiable List view of another List.


2. Set Interface

Sets are one of the essential part of Dart Collections. A set is defined as an unordered collection of unique objects.

Syntax:

Set<String> fruits = {"Mango", "Apple", "Banana"};

Example:

As discussed earlier a set stores a group of objects that are not repeating. A sample program is shown below.

Dart
void main() {
    // Initializing the Set and Adding the values
    Set geekSet = new Set();
    geekSet.addAll([9, 1, 2, 3, 4, 5, 6, 1, 1, 9]);
    
    // Looping over the set
    for (var el in geekSet) {
        print(el);
    }
    
    // length of the set.
    print('Length: ${geekSet.length}');
    
    // printing the first element in the set
    print('First Element: ${geekSet.first}');
    
    // Deleting an element not present. No Change
    geekSet.remove(10);
    
    // Deleting an element 9
    geekSet.remove(9);
    print(geekSet);
}

Output:

9
1
2
3
4
5
6
Length: 7
First Element: 9
{1, 2, 3, 4, 5, 6}


Classes Associated with Set Interfaces

Classes

Description

Set<E>

Collection of objects in which each of the objects occurs only once

HashSet<E>

Unordered set backed by a hash table

LinkedHashSet<E>

Ordered set that maintains insertion order

SplayTreeSet<E>

Automatically sorted set using a self-balancing binary search tree

UnmodifiableSetView<E>

Read-only view of a set


Hashset:

In the Dart programming language, a HashSet is a collection that stores a set of unique elements, where each element can be of any type. Here is an example of how to use a HashSet in Dart:

Dart
import 'dart:collection';

void main() {
    // Create a new HashSet
    var set = HashSet<String>();
    
    // Add some elements to the set
    set.add('apple');
    set.add('banana');
    set.add('cherry');
    
    // Check if an element is in the set
    print(set.contains('apple')); // Output: true
    print(set.contains('pear')); // Output: false
    
    // Iterate over the set
    set.forEach((element) {
        print(element);
    });
}

 Output:

true
false
apple
banana
cherry


3. Map Interface

In Dart, Maps are unordered key-value pair collections that set an associate key to the values within. To define a Map, specify the key type and the value type inside the angle brackets(<>) as shown below:

Syntax:

Map<int, String> fruits = {1: "Mango", 2: "Apple", 3: "Banana"};

Example:

The map collection stores the objects as a key-value pair. An example is shown below.

Dart
void main() {
    // Initializing the map with sample values.
    var geekMap = {1: "Apple", 2: "Mango", 3: "Banana"};
    print(geekMap);
    
    // Adding elements by different methods.
    geekMap.addAll({4: 'Pineapple', 2: 'Grapes'});
    geekMap[9] = "Kiwi";
    print(geekMap);
    
    // printing key and values
    print('Keys: ${geekMap.keys} \nValues: ${geekMap.values}');
    
    // removing an element from the map by its key
    geekMap.remove(2);
    
    // printing the map and its length
    print('{$geekMap} length is ${geekMap.length}');
}

Output:

{1: Apple, 2: Mango, 3: Banana}
{1: Apple, 2: Grapes, 3: Banana, 4: Pineapple, 9: Kiwi}
Keys: (1, 2, 3, 4, 9)
Values: (Apple, Grapes, Banana, Pineapple, Kiwi)
{{1: Apple, 3: Banana, 4: Pineapple, 9: Kiwi}} length is 4


Classes Associated with Map Interfaces

Classes

Description

MapBase<K, V>

This is the base class for Map

HashMap<K, V>

Unordered key-value store

LinkedHashMap<K, V>

Maintains insertion order

SplayTreeMap<K, V>

Sorted map based on keys

UnmodifiableMapBase<K, V>

Base class for read-only maps

UnmodifiableMapView<K, V>

Read-only view of a map

i. Hashmap 

In the Dart programming language, a HashMap is a collection that stores key-value pairs, where the keys are unique and the values can be of any type. Here is an example of how to use a HashMap in Dart:

Dart
import 'dart:collection';

void main() {
    // Create a new HashMap
    var map = HashMap<int, String>();
    
    // Add some key-value pairs to the map
    map[1] = 'one';
    map[2] = 'two';
    map[3] = 'three';
    
    // Access the value for a specific key
    print(map[1]); // Output: one
    
    // Iterate over the map
    map.forEach((key, value) {
        print('$key: $value');
    }); 
}

Output:

 one
1: one
2: two
3: three


4. Queue Interface

Queues are used to implement FIFO(First in First Out) collection. This collection can be manipulated from both ends.

Syntax:

import 'dart:collection';

Queue<String> queue = Queue.from(["Mango", "Apple", "Banana"]);

Example:

Dart
import 'dart:collection';

void main() {
    // Initializing the Set and Adding the values
    // We can also initialize a queue of a specific type
    // as Queue<int> q = new Queue();
    var geekQueue = new Queue();
    geekQueue.addAll([9, 1, 2, 3, 4, 5, 6, 1, 1, 9]);
    
    // Adds Element to the Start of the Queue
    geekQueue.addFirst("GFG");
    
    // Adds Element to the End of the Queue
    geekQueue.addLast("GFG2");
    print(geekQueue);
    
    // Removes the first Element
    geekQueue.removeFirst();
    print(geekQueue);
    
    // Removes the Last Element
    geekQueue.removeLast();
    print(geekQueue);
    
    // printing the first element in the set
    print('First Element: ${geekQueue.first}');
    
    // Looping over the set
    for (var el in geekQueue) {
        print(el);
    }
    
    // Other Operations
    // length of the set.
    print('Length: ${geekQueue.length}');
    
    // Deleting an element not present. No Change
    geekQueue.remove(10);
    
    // Deleting an element 9
    geekQueue.remove(2);
    print(geekQueue);
}


Output:

{GFG, 9, 1, 2, 3, 4, 5, 6, 1, 1, 9, GFG2}
{9, 1, 2, 3, 4, 5, 6, 1, 1, 9, GFG2}
{9, 1, 2, 3, 4, 5, 6, 1, 1, 9}
First Element: 9
9
1
2
3
4
5
6
1
1
9
Length: 10
{9, 1, 3, 4, 5, 6, 1, 1, 9}

Classes Associated with the Queue Interface

Classes

Description

DoubleLinkedQueue<E>

Doubly-linked list based on the queue data structure.


5. LinkedList Interface

It is a specialized, double-linked list of elements. This allows const time adding and removing at the either end also the time to increase the size is constant.

Syntax:

class MyEntry extends LinkedListEntry<MyEntry> {
final String value;
MyEntry(this.value);
}

LinkedList<MyEntry> list = LinkedList<MyEntry>();

Example:

Below is the implementation of a Doubly Linked List in Dart:

Dart
// Dart Program to Implement
// Doubly Linked List
import 'dart:collection';

// Class that extends LinkedListEntry.
// Each item in the LinkedList will be
// an instance of this class.
base class Box extends LinkedListEntry<Box> {
    final String contents;
    final int number;
    
    Box(this.contents, this.number);
}

void main() {
    final myLinkedList = LinkedList<Box>();
    
    // Adding elements to the LinkedList
    myLinkedList.add(Box('First Box', 1));
    myLinkedList.add(Box('Second Box', 2));
    myLinkedList.add(Box('Third Box', 3));
    
    // Iterating over the LinkedList
    for (final box in myLinkedList) {
        print(" ${box.contents} , ${box.number}");
    }
    
    // Remove an element from the LinkedList
    final boxToRemove = myLinkedList.firstWhere(
        (box) => box.contents == 'Second Box',
    );
    boxToRemove.unlink();
    
    print('');
    
    print('After removal:');
    for (final box in myLinkedList) {
        print(" ${box.contents} , ${box.number}");
    }
}

Output:

First Box , 1
Second Box , 2
Third Box , 3

After removal:
First Box , 1
Third Box , 3

Classes Associated with LinkedList Interface

Class

Description

LinkedListEntry<E extends LinkedListEntry<E>>

An element of a LinkedList.


Next Article
Article Tags :

Similar Reads