Open In App

Dart – Collections

Last Updated : 28 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
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 Dart Collection as mentioned below:

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 = new List();
  
  // We can also create a list with a predefined type
  // as List<int> sampleList = new List()
  // and also define a list of fixed length as
  // List<int> sampleList = new List(5)
  
  // 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 Set 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 fruits = Set.from("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>

Set based on hash table i.e unordered set.

LinkedHashSet<E>

Similar to HashSet but based on LinkedList.

SplayTreeSet<E>

Set based on Self Adjusting Binary Search Tree organizing elements to allow fast access.

UnmodifiableSetView<E>

Set that prevents any modifications.

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:

  apple
  banana
  cherry

3. Map Interface

In Dart, Maps are unordered key-value pair collection that sets 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>

Map based on hash table i.e unordered map.

LinkedHashMap<K, V>

Similar to HashMap but based on LinkedList.

SplayTreeMap<K, V>

The map ensures that its keys are ordered, and just like SplayTreeSet<E>.

UnmodifiableMapBase<K, V>

Basic implementation of an unmodifiable Map.

UnmodifiableMapView<K, V>

Unmodifiable view of the 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
 two
 three

4. Queue Interface

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

Syntax:

Queue<String> queue = new Queue("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}
Documentation 

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:

LinkedList<E extends LinkedListEntry<E>>

Example:

Below is the implementation of 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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads