The syntax of Map.putIfAbsent() method is:
V putIfAbsent(K key, V ifAbsent())
This putIfAbsent() method of Map look up the value of key
, or add a new entry if it isn't there.
Parameter | Optional/Required | Description |
---|---|---|
key | required | the key to look up or add |
ifAbsent | required | the function to generate the value if the key is absent |
Map.putIfAbsent() returns value of type V
.
In this example,
map
with some key-value pairs.putIfAbsent()
method to add a new entry with key 'three' and value 3 if 'three' is not already present in the map.putIfAbsent()
is printed, which is 3 in this case.map
is printed, showing the added entry.void main() {
Map<String, int> map = {'one': 1, 'two': 2};
int value = map.putIfAbsent('three', () => 3);
print(map); // Output: {one: 1, two: 2, three: 3}
}
{one: 1, two: 2, three: 3}
In this example,
map
with some key-value pairs.putIfAbsent()
method to add a new entry with key 3 and value 'Three' if 3 is not already present in the map.putIfAbsent()
is printed, which is 'Three' in this case.map
is printed, showing the added entry.void main() {
Map<int, String> map = {1: 'One', 2: 'Two'};
String value = map.putIfAbsent(3, () => 'Three');
print(map); // Output: {1: One, 2: Two, 3: Three}
}
{1: One, 2: Two, 3: Three}
In this example,
map
with some key-value pairs.putIfAbsent()
method to add a new entry with key 'taste' and value 'sweet' if 'taste' is not already present in the map.putIfAbsent()
is printed, which is 'sweet' in this case.map
is printed, showing the added entry.void main() {
Map<String, String> map = {'fruit': 'apple', 'color': 'red'};
String value = map.putIfAbsent('taste', () => 'sweet');
print(map); // Output: {fruit: apple, color: red, taste: sweet}
}
{fruit: apple, color: red, taste: sweet}
In this Dart tutorial, we learned about putIfAbsent() method of Map: the syntax and few working examples with output and detailed explanation for each example.