Menu
Coddy logo textTech

Conditional Add: putIfAbsent

Part of the Logic & Flow section of Coddy's Dart journey — lesson 29 of 65.

Sometimes you need to add a key-value pair to a Map, but only if that key doesn't already exist. The putIfAbsent() method handles this situation perfectly by adding the entry only when the key is missing from the map.

This method takes two parameters: the key to check for, and the value to add if the key is absent. If the key already exists, putIfAbsent() does nothing and leaves the existing value unchanged. If the key is missing, it adds the new key-value pair to the map.

Map<String, int> gameScores = {
  'Alice': 150,
  'Bob': 200
};

// This will add Charlie since he's not in the map
gameScores.putIfAbsent('Charlie', () => 0);
print(gameScores);  // {Alice: 150, Bob: 200, Charlie: 0}

// This won't change Alice's score since she already exists
gameScores.putIfAbsent('Alice', () => 0);
print(gameScores);  // {Alice: 150, Bob: 200, Charlie: 0}

The putIfAbsent() method is particularly useful for initializing default values, such as setting up new user accounts or ensuring certain keys exist before performing operations on them. It's a safe way to add data without accidentally overwriting existing information.

challenge icon

Challenge

Easy

Create a program that manages a gaming tournament registration system by tracking player scores and ensuring all players have default starting values. Your program should:

  1. Read a string input representing the tournament name
  2. Read multiple pairs of inputs representing player names and their current scores (the input will end when you receive "scores_done")
  3. Read multiple string inputs representing new players who want to join the tournament (the input will end when you receive "players_done")
  4. Create a Map to store player names as keys and their scores as values
  5. Use the putIfAbsent() method to add each new player with a default score of 0, but only if they're not already registered
  6. Calculate tournament statistics and print the registration report in the exact format shown below

For example, if the tournament name is "Spring Championship", the existing scores include "Alice" with 150, "Bob" with 200, "Charlie" with 75, and the new players are "Diana", "Alice", "Eve", your program should output:

Tournament: Spring Championship
Initial Scores: {Alice: 150, Bob: 200, Charlie: 75}
Registration Process:
Adding Diana: New player registered with score 0
Adding Alice: Player already exists, keeping score 150
Adding Eve: New player registered with score 0
Final Scores: {Alice: 150, Bob: 200, Charlie: 75, Diana: 0, Eve: 0}
Tournament Statistics:
Total registered players: 5
Players with scores above 0: 3
New players added: 2
Average score: 85.0
Status: Registration completed successfully

If the tournament name is "Winter Cup", the existing scores include "John" with 300, "Mary" with 250, and the new players are "Sarah", "Tom", "John", your program should output:

Tournament: Winter Cup
Initial Scores: {John: 300, Mary: 250}
Registration Process:
Adding Sarah: New player registered with score 0
Adding Tom: New player registered with score 0
Adding John: Player already exists, keeping score 300
Final Scores: {John: 300, Mary: 250, Sarah: 0, Tom: 0}
Tournament Statistics:
Total registered players: 4
Players with scores above 0: 2
New players added: 2
Average score: 137.5
Status: Registration completed successfully

If the tournament name is "Summer League", the existing scores include "Alex" with 180, "Jordan" with 220, "Taylor" with 160, "Morgan" with 190, and the new players are "Casey", "Riley", your program should output:

Tournament: Summer League
Initial Scores: {Alex: 180, Jordan: 220, Taylor: 160, Morgan: 190}
Registration Process:
Adding Casey: New player registered with score 0
Adding Riley: New player registered with score 0
Final Scores: {Alex: 180, Jordan: 220, Taylor: 160, Morgan: 190, Casey: 0, Riley: 0}
Tournament Statistics:
Total registered players: 6
Players with scores above 0: 4
New players added: 2
Average score: 158.33333333333334
Status: Registration completed successfully

Your program must use the putIfAbsent() method to add new players with a default score of 0, ensuring that existing players keep their current scores unchanged. Calculate the average score by dividing the total of all scores by the number of players. Count how many players have scores above 0 and how many new players were actually added (excluding those who were already registered). The input format will be: tournament name, then alternating player names and scores (as strings that need to be converted to integers), ending with "scores_done", followed by new player names ending with "players_done".

Cheat sheet

The putIfAbsent() method adds a key-value pair to a Map only if the key doesn't already exist:

Map<String, int> gameScores = {
  'Alice': 150,
  'Bob': 200
};

// Adds Charlie since he's not in the map
gameScores.putIfAbsent('Charlie', () => 0);

// Won't change Alice's score since she already exists
gameScores.putIfAbsent('Alice', () => 0);

This method is useful for initializing default values without overwriting existing data.

Try it yourself

import 'dart:io';

void main() {
  // Read tournament name
  String? tournamentName = stdin.readLineSync();
  
  // Create a map to store player scores
  Map<String, int> playerScores = {};
  
  // Read existing player scores
  while (true) {
    String? input = stdin.readLineSync();
    if (input == "scores_done") break;
    
    String playerName = input!;
    String? scoreInput = stdin.readLineSync();
    int score = int.parse(scoreInput!);
    playerScores[playerName] = score;
  }
  
  // Store initial scores for display
  Map<String, int> initialScores = Map.from(playerScores);
  
  // Read new players to register
  List<String> newPlayers = [];
  while (true) {
    String? input = stdin.readLineSync();
    if (input == "players_done") break;
    newPlayers.add(input!);
  }
  
  // TODO: Write your code below
  // Use putIfAbsent() method to add new players with default score 0
  // Track registration process and calculate statistics
  
  // Print the tournament registration report
  print("Tournament: $tournamentName");
  print("Initial Scores: $initialScores");
  print("Registration Process:");
  // Print registration process details here
  print("Final Scores: $playerScores");
  print("Tournament Statistics:");
  // Print statistics here
  print("Status: Registration completed successfully");
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow