The containsKey()
method in Dart checks if an entry for the specified key is present in SplayTreeMap
.
bool containsKey(Object? key)
Argument: This is the key
to be searched and passed as an argument.
This method returns true
if there is an entry for the provided key
. Otherwise, it returns false
.
The code below demonstrates how to use containsKey()
to check if there is an entry present for the specified key:
import 'dart:collection';void main() {//Create a new SplayTreeMap that can have the int key and string valuesSplayTreeMap map = new SplayTreeMap<int, String>((keya,keyb) => keyb.compareTo(keya));// Add five entries to the mapmap[5] = "Five";map[4] = "Four";map[2] = "Two";map[1] = "One";map[3] = "Three";print('The map is $map');print('map.containsKey(5) : ${map.containsKey(5)}');print('map.containsKey(10) : ${map.containsKey(10)}');}
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 order of the map
entries. In our case, the compare
function orders the elements in descending order.
Lines 7 to 11: We add five new entries to the map
. Now, the map is _{5=Five,4=Four,3=Three,2=Two,1=One}_
.
Line 15: We use the containsKey()
method to check if the map
contains an entry for the key 5
. The map has an entry for the key 5
, so the methods returns true
.
Line 16: We use the containsKey()
method to check if the map
contains an entry for the key 10
. The map doesn’t have an entry for the key 10
, so the method returns false
.