How to remove an entry of the SplayTreeMap in Dart?

Overview

The remove() method removes an entry from the SplayTreeMap.

Syntax

V? remove(Object? key)

Parameters

This method takes the key whose entry is to be removed.

Return type

  • If there is an entry present for the specified key, the entry is removed, and the value associated with the key is returned.

  • If there is no entry present for the specified key, null is returned.

HashMap allows null as a value. Hence, a returned null value doesn’t always mean that the key is absent.

Code

The code below demonstrates the use of the remove() method to remove an entry from the SplayTreeMap:

import 'dart:collection';
void main() {
//create a new SplayTreeMap which can have int key and string values
SplayTreeMap map = new SplayTreeMap<int, String>((keya,keyb) => keyb.compareTo(keya));
// add five entries to the map
map[5] = "Five";
map[4] = "Four";
map[2] = "Two";
map[1] = "One";
map[3] = "Three";
print('The map is $map');
// Remove the entry with key 1
print('map.remove(1) is ${map.remove(1)}');
print('The map is $map');
// Remove the entry with key 10
print('\nmap.remove(10) is ${map.remove(10)}');
print('The map is $map');
}

Explanation

Line 1: We import the collection library.

Line 4: We create a new SplayTreeMap object named map. We pass a compare function as an argument. This function maintains the map entries’ order. In our case, the compare function orders the elements in descending order.

Lines 7–11: We add five new entries to the map. Now, the map is {5=Five,4=Four,3=Three,2=Two,1=One}.

Line 16: We use the remove method with 1 as an argument. This checks if the map has an entry with the key 1. In our case, there is an entry with 1. Therefore, the entry with the key 1 is removed. The value One associated with the key is returned. Now, the map is {5: Five, 4: Four, 3: Three, 2: Two}.

Line 20: We use the remove method with 10 as an argument. This checks if the map has an entry with the key 10. In our case, there is no entry with 10 on the map. Therefore, null is returned.

Free Resources