Removing Entries from a Map
Part of the Logic & Flow section of Coddy's Dart journey — lesson 30 of 65.
When managing data in a Map, you'll often need to remove entries that are no longer needed. The remove() method provides a straightforward way to delete a key-value pair from a map using its key.
The remove() method takes a single parameter: the key of the entry you want to delete. When called, it removes both the key and its associated value from the map. If the key doesn't exist in the map, the method simply does nothing without causing an error.
Map<String, double> inventory = {
'Laptop': 999.99,
'Mouse': 25.50,
'Keyboard': 75.00
};
// Remove the mouse from inventory
inventory.remove('Mouse');
print(inventory); // {Laptop: 999.99, Keyboard: 75.0}
// Trying to remove a non-existent item does nothing
inventory.remove('Tablet');
print(inventory); // {Laptop: 999.99, Keyboard: 75.0}This method is essential for maintaining clean, up-to-date maps in your applications. Whether you're managing inventory, user data, or any other collection where items need to be removed, remove() provides a safe and efficient way to delete entries by their key.
Challenge
EasyCreate a program that manages a digital music streaming service by tracking song libraries and removing songs that are no longer available due to licensing issues. Your program should:
- Read a string input representing the streaming service name
- Read multiple pairs of inputs representing song titles and their streaming counts (the input will end when you receive
"library_done") - Read multiple string inputs representing songs to be removed due to licensing issues (the input will end when you receive
"removal_done") - Create a Map to store song titles as keys and their streaming counts as values
- Use the
remove()method to remove each specified song from the library - Calculate library statistics and print the removal report in the exact format shown below
For example, if the service name is "MusicStream Pro", the library includes "Bohemian Rhapsody" with 2500000 streams, "Imagine" with 1800000 streams, "Hotel California" with 2200000 streams, "Stairway to Heaven" with 1900000 streams, and the songs to remove are "Imagine", "Yesterday", "Hotel California", your program should output:
Service: MusicStream Pro
Original Library: {Bohemian Rhapsody: 2500000, Imagine: 1800000, Hotel California: 2200000, Stairway to Heaven: 1900000}
Removal Process:
Removing 'Imagine': Song removed (had 1800000 streams)
Removing 'Yesterday': Song not found in library
Removing 'Hotel California': Song removed (had 2200000 streams)
Updated Library: {Bohemian Rhapsody: 2500000, Stairway to Heaven: 1900000}
Library Statistics:
Songs before removal: 4
Songs after removal: 2
Songs successfully removed: 2
Songs not found: 1
Total streams lost: 4000000
Remaining total streams: 4400000
Status: Library update completedIf the service name is "SoundWave", the library includes "Shape of You" with 3200000 streams, "Blinding Lights" with 2800000 streams, "Someone Like You" with 2100000 streams, and the songs to remove are "Blinding Lights", "Perfect", your program should output:
Service: SoundWave
Original Library: {Shape of You: 3200000, Blinding Lights: 2800000, Someone Like You: 2100000}
Removal Process:
Removing 'Blinding Lights': Song removed (had 2800000 streams)
Removing 'Perfect': Song not found in library
Updated Library: {Shape of You: 3200000, Someone Like You: 2100000}
Library Statistics:
Songs before removal: 3
Songs after removal: 2
Songs successfully removed: 1
Songs not found: 1
Total streams lost: 2800000
Remaining total streams: 5300000
Status: Library update completedIf the service name is "AudioHub", the library includes "Bad Guy" with 1500000 streams, "Watermelon Sugar" with 1700000 streams, "Levitating" with 1400000 streams, "Good 4 U" with 1600000 streams, and the songs to remove are "Bad Guy", "Levitating", "Good 4 U", "Drivers License", your program should output:
Service: AudioHub
Original Library: {Bad Guy: 1500000, Watermelon Sugar: 1700000, Levitating: 1400000, Good 4 U: 1600000}
Removal Process:
Removing 'Bad Guy': Song removed (had 1500000 streams)
Removing 'Levitating': Song removed (had 1400000 streams)
Removing 'Good 4 U': Song removed (had 1600000 streams)
Removing 'Drivers License': Song not found in library
Updated Library: {Watermelon Sugar: 1700000}
Library Statistics:
Songs before removal: 4
Songs after removal: 1
Songs successfully removed: 3
Songs not found: 1
Total streams lost: 4500000
Remaining total streams: 1700000
Status: Library update completedYour program must use the remove() method to delete songs from the Map. Track which songs were successfully removed and which were not found. Calculate the total streams lost by summing the streaming counts of successfully removed songs. The input format will be: service name, then alternating song titles and streaming counts (as strings that need to be converted to integers), ending with "library_done", followed by song titles to remove ending with "removal_done".
Cheat sheet
The remove() method deletes a key-value pair from a Map using its key:
Map<String, double> inventory = {
'Laptop': 999.99,
'Mouse': 25.50,
'Keyboard': 75.00
};
// Remove entry by key
inventory.remove('Mouse');
print(inventory); // {Laptop: 999.99, Keyboard: 75.0}
// Removing non-existent key does nothing
inventory.remove('Tablet');
print(inventory); // {Laptop: 999.99, Keyboard: 75.0}The method safely handles non-existent keys without causing errors.
Try it yourself
import 'dart:io';
void main() {
// Read service name
String? serviceName = stdin.readLineSync();
// Create a Map to store song titles and streaming counts
Map<String, int> songLibrary = {};
// Read song library data
while (true) {
String? input = stdin.readLineSync();
if (input == "library_done") break;
String songTitle = input!;
String? streamCountStr = stdin.readLineSync();
int streamCount = int.parse(streamCountStr!);
songLibrary[songTitle] = streamCount;
}
// Read songs to remove
List<String> songsToRemove = [];
while (true) {
String? input = stdin.readLineSync();
if (input == "removal_done") break;
songsToRemove.add(input!);
}
// TODO: Write your code below
// Process the removal of songs using the remove() method
// Track statistics and generate the required output format
// Print the results in the required format
// Remember to include: Service name, Original Library, Removal Process,
// Updated Library, and Library Statistics
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List