The putIfAbsent
method adds the key-value pair to the SplayTreeMap
if an entry for the provided key is not present in the map.
If the key is already present, then it skips the operation.
V putIfAbsent(K key, V ifAbsent())
This method takes two parameters.
key
: This is the key for which value is to be added if there is no entry already available.
ifAbsent
: This function will be invoked when there is no entry for the key present in the map. This method should return a value. That value is used when we add a new entry.
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.
The code below demonstrates how to use the putIfAbsent
method:
import 'dart:collection';void main() {//create a new SplayTreeMap which can have 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";print('The map is $map');print('\nCalling put if absent for key 5');// using putIfAbsent to add entry for key 5var result = map.putIfAbsent(5, ()=> "Six");print('map.putIfAbsent(5, ()=> "Six") : $result');print('The map is $map');print('\nCalling put if absent for key 1');// using putIfAbsent to add entry for key 1result = map.putIfAbsent(1, ()=> "One");print('map.putIfAbsent(1, ()=> "One") : $result');print('The map is $map');}
Line 1: We import the collection
library.
Line 4: We create a new SplayTreeMap
object with the name map
. We pass a compare
function as an argument. This function is used for maintaining the order of the map
entries. In our case, the compare
function orders the elements in descending order.
Lines 7–8: We add two new entries to the map
. Now, the map is {5=Five, 4=Four}
.
Line 14: We use the puIfAbsent
method with the following paramters:
5
as the key
.ifAbsent
function returns Six
as a return value.In our case, there is an entry already available for the key 5
. The old value Five
associated with the key 5
is returned.
Line 20: We use the puIfAbsent
method with the following parameters:
1
as the key
.ifAbsent
function returns One
as a return value.In our case, there is no entry available for the key 1
. So a new entry with key 1
and value One
is added to map
and the new value One
is returned. Now, map
is {5: Five, 4: Four, 1: One}
.