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 value
HashMap map = new HashMap<String, int>();
// add two entries to the map
map["one"] = 1;
map["two"] = 2;
print('The map is $map');
// check if the map has a value 1
print('map.containsValue(1) is ${map.containsValue(1)}');
// check if the map has a value 3
print('map.containsValue(2) is ${map.containsValue(3)}');
}

Explanation

  • Line 1: We import the collection library.

  • Line 4: We create a new HashMap object with the name map.

  • Lines 7 and 8: We add two new entries to the map.

  • Line 12: We used the containsValue method with 1 as an argument. This checks if the map has an entry with the value 1. In our code, there is an entry with the value 1. Hence, true is returned.

  • Line 13: We use the containsValue method with 3 as an argument. This checks if the map has an entry with the value 3. In our code, there is no entry with value 3 in the map so false is returned.

Free Resources