Adding and Removing from Sets
Part of the Logic & Flow section of Coddy's Dart journey — lesson 19 of 65.
Once you have a Set, you'll often need to modify its contents by adding new elements or removing existing ones. The add() and remove() methods provide straightforward ways to manage your set's elements.
The add() method attempts to insert a new element into the set. However, since sets only store unique values, if you try to add an element that already exists, the method simply does nothing - no error occurs, and the set remains unchanged.
Set<String> usernames = {'alice', 'bob', 'charlie'};
usernames.add('diana'); // Adds 'diana' successfully
usernames.add('alice'); // Does nothing - 'alice' already exists
print(usernames); // {alice, bob, charlie, diana}The remove() method works by taking the value you want to delete and removing it from the set. If the element doesn't exist in the set, the method simply does nothing, making it safe to use without checking first.
usernames.remove('bob'); // Removes 'bob'
usernames.remove('unknown'); // Does nothing - element not found
print(usernames); // {alice, charlie, diana}Challenge
EasyCreate a program that manages a team collaboration system by adding new team members and removing inactive ones from a project team. Your program should:
- Read a string input representing the project name
- Read multiple string inputs representing initial team members (the input will end when you receive
"initial_done") - Read multiple string inputs representing new members to add (the input will end when you receive
"add_done") - Read multiple string inputs representing members to remove (the input will end when you receive
"remove_done") - Create a Set with the initial team members
- Use the
add()method to add each new member to the team - Use the
remove()method to remove each specified member from the team - Print the team management results in the exact format shown below
For example, if the project name is "Mobile App Development", the initial members are "Alice", "Bob", "Charlie", the new members to add are "Diana", "Alice", "Eve", and the members to remove are "Bob", "Frank", your program should output:
Project: Mobile App Development
Initial team: {Alice, Bob, Charlie}
Adding new members: [Diana, Alice, Eve]
After adding members: {Alice, Bob, Charlie, Diana, Eve}
Removing members: [Bob, Frank]
Final team: {Alice, Charlie, Diana, Eve}
Team size: 4
Status: Team updated successfullyIf the project name is "Website Redesign", the initial members are "John", "Sarah", the new members to add are "Mike", "John", and the members to remove are "Sarah", "Unknown", your program should output:
Project: Website Redesign
Initial team: {John, Sarah}
Adding new members: [Mike, John]
After adding members: {John, Sarah, Mike}
Removing members: [Sarah, Unknown]
Final team: {John, Mike}
Team size: 2
Status: Team updated successfullyIf the project name is "Data Analysis", the initial members are "Emma", the new members to add are "Tom", "Lisa", and the members to remove are "Emma", your program should output:
Project: Data Analysis
Initial team: {Emma}
Adding new members: [Tom, Lisa]
After adding members: {Emma, Tom, Lisa}
Removing members: [Emma]
Final team: {Tom, Lisa}
Team size: 2
Status: Team updated successfullyYour program must demonstrate that the add() method does nothing when trying to add a member who already exists, and the remove() method does nothing when trying to remove a member who doesn't exist. Store the input lists to show what operations were attempted, then show the Set contents after each operation to demonstrate the unique nature of Sets.
Cheat sheet
Use add() to insert elements into a Set. If the element already exists, nothing happens:
Set<String> usernames = {'alice', 'bob', 'charlie'};
usernames.add('diana'); // Adds 'diana' successfully
usernames.add('alice'); // Does nothing - 'alice' already exists
print(usernames); // {alice, bob, charlie, diana}Use remove() to delete elements from a Set. If the element doesn't exist, nothing happens:
usernames.remove('bob'); // Removes 'bob'
usernames.remove('unknown'); // Does nothing - element not found
print(usernames); // {alice, charlie, diana}Try it yourself
import 'dart:io';
void main() {
// Read project name
String? projectName = stdin.readLineSync();
// Read initial team members
List<String> initialMembers = [];
String? member;
while ((member = stdin.readLineSync()) != "initial_done") {
initialMembers.add(member!);
}
// Read new members to add
List<String> membersToAdd = [];
while ((member = stdin.readLineSync()) != "add_done") {
membersToAdd.add(member!);
}
// Read members to remove
List<String> membersToRemove = [];
while ((member = stdin.readLineSync()) != "remove_done") {
membersToRemove.add(member!);
}
// TODO: Write your code below
// Create a Set with initial team members
// Add new members using add() method
// Remove members using remove() method
// Print the results in the required format
print("Project: $projectName");
// Add remaining print statements here
}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