How to check the map for a specific value in Dart
In Dart, the containsValue method is used to check if the map contains a specific value.
Syntax
bool containsValue(Object? value)
Parameters
This method takes the argument, value, which represents the value that we want to check for.
Return value
This method returns true if the passed value is equal to any of the values in the map.
We use the == operator for that.
Example
The code below demonstrates how to check if the HashMap contains an entry with a specific value:
import 'dart:collection';void main() {//create a new hashmap which can have string type as key, and int type as valueHashMap map = new HashMap<String, int>();// add two entries to the mapmap["one"] = 1;map["two"] = 2;print('The map is $map');// check if the map has a value 1print('map.containsValue(1) is ${map.containsValue(1)}');// check if the map has a value 3print('map.containsValue(2) is ${map.containsValue(3)}');}
Explanation
-
Line 1: We import the
collectionlibrary. -
Line 4: We create a new
HashMapobject with the namemap. -
Lines 7 and 8: We add two new entries to the
map. -
Line 12: We used the
containsValuemethod with1as an argument. This checks if the map has an entry with the value1. In our code, there is an entry with the value1. Hence,trueis returned. -
Line 13: We use the
containsValuemethod with3as an argument. This checks if the map has an entry with the value3. In our code, there is no entry with value3in the map sofalseis returned.