Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator

What is map.putIfAbsent() in Dart?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The putIfAbsent() method

In Dart, the putIfAbsent() method checks the value of key or creates one if it doesn’t exist.

Syntax


V putIfAbsent (K key, V ifAbsent())

Parameters and return value

If there is a value associated with key, it is returned. Otherwise, it uses ifAbsent() to get a new value, associates key with it, and returns the new value.

Code

void main() {
Map<String, int> age = {'Eva': 16};
print('The orignal map: ${age}');
for (var key in ['Tobby', 'Eddie', 'Maria']) {
age.putIfAbsent(key, () => key.length * 2);
}
print('The new map:${age}');
}

Explanation

  • In the code above, we create a map named age.

  • Next, we use the for loop to iterate over the iterable and pass the putIfAbsent method, which returns the value associated to key, if there is one.

  • Otherwise, it calls ifAbsent to get a new value, associates key with it, and returns the new value.

RELATED TAGS

dart
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring