Dart Map putIfAbsent()
Syntax & Examples

Syntax of Map.putIfAbsent()

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.

Parameters

ParameterOptional/RequiredDescription
keyrequiredthe key to look up or add
ifAbsentrequiredthe function to generate the value if the key is absent

Return Type

Map.putIfAbsent() returns value of type V.



✐ Examples

1 Add key-value pair if key is absent

In this example,

  1. We create a map map with some key-value pairs.
  2. We use the putIfAbsent() method to add a new entry with key 'three' and value 3 if 'three' is not already present in the map.
  3. The value returned by putIfAbsent() is printed, which is 3 in this case.
  4. The updated map map is printed, showing the added entry.

Dart Program

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}
}

Output

{one: 1, two: 2, three: 3}

2 Add key-value pair if key is absent

In this example,

  1. We create a map map with some key-value pairs.
  2. We use the putIfAbsent() method to add a new entry with key 3 and value 'Three' if 3 is not already present in the map.
  3. The value returned by putIfAbsent() is printed, which is 'Three' in this case.
  4. The updated map map is printed, showing the added entry.

Dart Program

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}
}

Output

{1: One, 2: Two, 3: Three}

3 Add key-value pair if key is absent

In this example,

  1. We create a map map with some key-value pairs.
  2. We use the putIfAbsent() method to add a new entry with key 'taste' and value 'sweet' if 'taste' is not already present in the map.
  3. The value returned by putIfAbsent() is printed, which is 'sweet' in this case.
  4. The updated map map is printed, showing the added entry.

Dart Program

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}
}

Output

{fruit: apple, color: red, taste: sweet}

Summary

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.