LinkedHashMap's containsKey and containsValue method in Dart
A LinkedHashMap is a
hash-tablebased implementation of. The LinkedHashMap maintains the insertion order of entries. We can read more about the concept of a Map Map contains a list of key-value pairs as an element. LinkedHashMaphere.
The containsKey method is used to check if the LinkedHashMap contains a specific key.
The containsValue method is used to check if the LinkedHashMap contains a specific value.
Synax
// check if the key is present
bool containsKey(Object? key)
// check if the value is present
bool containsValue(Object? value)
Argument
The containsKey method takes the key whose presence needs to be checked in the LinkedHashMap as an argument.
The containsValue method takes the value whose presence needs to be checked in the LinkedHashMap, as an argument.
Return value
This method returns True if the passed key/value is present in the LinkedHashMap.
Code
The code written below demonstrates how we can use the containsKey and containsValue method of the LinkedHashMap:
import 'dart:collection';void main() {//create a new LinkedHashmap which can have string type as key, and int type as valueLinkedHashMap map = new LinkedHashMap<String, int>();// add two entries to the mapmap["one"] = 1;map["two"] = 2;print('The map is $map');// Using the "containsKey" mehod to check if the map has a specific keyprint('\nmap.containsKey("one") is ${map.containsKey("one")}');print('map.containsKey("three") is ${map.containsKey("three")}');// Using the "containsValue" mehod to check if the map has a specific valueprint('\nmap.containsValue(1) is ${map.containsValue(1)}');print('map.containsValue(3) is ${map.containsValue(3)}');}
Explanation
In the code written above:
-
In line 1, we import the
collectionlibrary. -
In line 4, we create a new
LinkedHashMapobject with the namemap. -
In lines 7 and 8, we add two new entries to the
map. -
In line 12, we use the
containsKeymethod withoneas an argument. This will check if the map has an entry with the keyone. In our case, there is an entry with the keyone, soTrueis returned. -
In line 13, we use the
containsKeymethod withthreeas an argument. This will check if the map has an entry with the keythree. In our case, there is no entry with the keythreein the map, soFalseis returned. -
In line 16, we use the
containsValuemethod with1as an argument. This will check if the map has an entry with the value1. In our case, there is an entry with the value1, soTrueis returned. -
In line 17, we use the
containsValuemethod with3as an argument. This will check if the map has an entry with the value3. In our case, there is no entry with the value3in the map, soFalseis returned.