What is HashMap.putIfAbsent in Dart?
A Hash-table-based implementation of
. Read more about HashMap here. Map Map contains a list of key-value pairs as an element.
The putIfAbsent method adds a key-value pair to a map if the key is not present in the map.
If the key is already present, then it skips the operation.
Syntax
V putIfAbsent(K key, V ifAbsent())
Arguments
This method takes two arguments.
-
key: Thekey, together with its value, that is added if there is no entry already available. -
ifAbsent: A function that will be invoked when no entry for the key is present in the map. This method will return a value, which will be used when adding a new entry.
Return value
If the key is already present in the map, then the old value associated with the key is returned and insertion will be skipped.
If the key is not present in the map, then a new key-value pair is inserted and the new value is returned.
Code
The code below demonstrates how to use the putIfAbsent method:
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');print('\nCalling put if absent for key "one"');// using putIfAbsent to add entry for key "one"var result = map.putIfAbsent("one", ()=> 10);print('map.putIfAbsent("one", ()=> 10) : $result');print('The map is $map');print('\nCalling put if absent for key "three"');// using putIfAbsent to add entry for key "three"result = map.putIfAbsent("three", ()=> 3);print('map.putIfAbsent("one", ()=> 10) : $result');print('The map is $map');}
Explanation
In the code above,
-
In line 1, we import the
collectionlibrary. -
In line 4, we create a new
HashMapobject with the namemap. -
In lines 7-8, we add two new entries to the
map. Now the map is{one: 1, two: 2} -
In line 14, we use the
puIfAbsentmethod with the following arguments:oneaskeyifAbsentfunction which returns 10 as return value.
In our case, there is an entry already present for the key one. Therefore, the old value associated with the key one, i.e. 1, is returned.
- In line 20, we use the
puIfAbsentmethod with the following arguments:threeaskeyifAbsentfunction returns three as a return value.
In our case, there is no entry available for the key three. So a new entry with key three and value 3 is added to the map, and the new value 3 is returned. Now the map will be {three: 3, one: 1, two: 2}.