Golang Program to Delete items of Map


Maps in Go provide a convenient way to store and access data in form of key−value pairs. Deleting items from a map is a common operation when working with dynamic data. In this article, we will delete items of map in golanguage using three methods: the delete() function and iterating over the map, to remove items from a map, and creating a new map based on different conditions.

Explanation

Maps are versatile structures for holding key−value pairs, and managing these pairs is crucial when dealing with dynamic data. We'll use three approaches to removing items from a map, enhancing our map data manipulation skills.

delete() Function Method

The delete() function is a direct and effective way to eliminate a key−value pair from a map. By specifying the key to delete, you can promptly remove the corresponding data from the map.

Iterative Removal

Iterating over the keys of a map and selectively removing items based on specific conditions provides flexibility in data management. If you need to eliminate multiple items that match certain criteria, this method is beneficial.

Creating a New Map

To maintain data integrity and derive a refined map, you can create a new map by filtering out unwanted items. By examining each key−value pair and only copying over those that meet specific criteria, you generate a fresh map while preserving the original data.

Syntax

 delete(mapName, key)

This syntax deletes map items from mapName based on a specific condition. It iterates over each key in the map and checks the condition. If the condition is true, the corresponding key−value pair is deleted using the delete keyword.

newMap := make(map[keyType]valueType)

This syntax newMap := make(map[keyType]valueType) creates a new map named newMap using the make() function.

Algorithm

  • Accept the map name and the key to be deleted as inputs.

  • Use the delete keyword followed by the map name and the specified key to delete the corresponding key−value pair from the map.

  • The map is updated with the specified key−value pair deleted.

Example

In this example, we can deleta the items from maps using a key, let us consider a map named fruitMap that stores the names of fruits as keys and their corresponding quantities as values. We want to delete the entry for the fruit "apple" from the map.

package main

import "fmt"

func main() {
	fruitMap := map[string]int{
		"apple":  5,
		"banana": 3,
		"orange": 2,
	}

	delete(fruitMap, "apple")

	fmt.Println("Updated Fruit Map:", fruitMap)
}

Output

Updated Fruit Map: map[banana:3 orange:2]

Example

In this example we iterate over the keys of the map and check the condition for each key−value pair to delete items of map in golanguage. If the condition is satisfied, we delete the corresponding key−value pair using the delete keyword. Let us consider a map named studentScores that stores the names of students as keys and their corresponding scores as values. We want to delete the entries for students who scored below 60.

package main

import "fmt"

func main() {
	studentScores := map[string]int{
		"John":    80,
		"Alice":   55,
		"Michael": 75,
		"Sara":    65,
	}

	for name, score := range studentScores {
		if score < 60 {
			delete(studentScores, name)
		}
	}

	fmt.Println("Updated Student Scores:", studentScores)
}

Output

Updated Student Scores: map[John:80 Michael:75 Sara:65]

Example

In this example, consider a map named cityPopulation that stores the names of cities as keys and their corresponding populations as values. In the map we want to delete the entries for cities with a population below 1 million.

package main

import "fmt"

func main() {
	cityPopulation := map[string]int{
		"New York":     8623000,
		"Los Angeles":  3990456,
		"Chicago":      2716000,
		"Houston":      2312717,
		"Philadelphia": 1579000,
	}

	newCityPopulation := make(map[string]int)
	for city, population := range cityPopulation {
		if population >= 1000000 {
			newCityPopulation[city] = population
		}
	}

	fmt.Println("Updated City Population:", newCityPopulation)
}

Output

Updated City Population: map[Chicago:2716000 Houston:2312717 Los Angeles:3990456 New York:8623000 Philadelphia:1579000]

Real life Implementation

E−commerce Inventory Management

Suppose you're building an e−commerce platform, and you have a map that stores the product IDs as keys and their corresponding quantities in stock as values. When a customer places an order, you need to update the inventory. If a product is sold out, you want to remove it from the inventory.

User Account Management

Imagine you're developing a user management system for a website. You have a map that stores user IDs as keys and their account status (active or inactive) as values. When a user decides to deactivate their account, you need to update the map accordingly.

Conclusion

In this article we are going to look at how we can delete items of map in golanguage: using the delete() function to remove specific key−value pairs, iterating over the map to delete items based on conditions, and creating a new map without the items we want to delete. These methods offer different approaches to managing map data and used in e−commerce management where the product has to be stored by a specific id, as well as in account management where the user id is unique and is connected with the user data.

Updated on: 07-Sep-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements