Go Language - Maps - Example

A map is an unordered collection of key/value pairs, where each key is unique. We can create a new map with a make statement or a map literal. The default zero value of a map is nil. The len function returns the size of a map. Go Range keyword is used in different kinds of data structures in order to iterate over elements.

Create a Map:

Create a Map called users that will store int keys and String values:
/* Create a new map
* Empty map of string-string pairs
*/
users := make(map[int]string)

Add Items:

Add a new key-value pair,
//Add Items
users[1] = "scott"
users[2] = "june"
users[3] = "april"
users[4] = "carl"
users[5] = "rick"
users[6] = "daryl"

Update Value:

// Update value
users[6] = "michonne"

Iterate over all keys and values:

// Iterating over all keys and values
for id, name := range users {
fmt.Printf("id :%d name: %s\n", id, name)
}

Access an Item:

//Access an Item
fmt.Println("\n", users[1], "\n")

Remove an Item:

//Remove an Item
delete(users, 3)

Test if entry is present in the map or not:

// Test if entry is present in the map or not
_, status := users[4]
fmt.Println("\n", status, "\n")


Complete Code:

package main

import "fmt"

//Required imports

func main() {

/* Create a new map
* Empty map of string-string pairs
*/
users := make(map[int]string)

//Add Items
users[1] = "scott"
users[2] = "june"
users[3] = "april"
users[4] = "carl"
users[5] = "rick"
users[6] = "daryl"

fmt.Println("\n")

// Iterating over all keys and values
for id, name := range users {
fmt.Printf("id :%d name: %s\n", id, name)
}

// Update value
users[6] = "michonne"

fmt.Println("\n")

// Iterating over all keys and values
for id, name := range users {
fmt.Printf("id :%d name: %s\n", id, name)
}

//Access an Item
fmt.Println("\n", users[1], "\n")

//Remove an Item
delete(users, 3)

// Iterating over all keys and values
for id, name := range users {
fmt.Printf("id :%d name: %s\n", id, name)
}

// Test if entry is present in the map or not
_, status := users[4]
fmt.Println("\n", status, "\n")
}

Output:

Comments

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java, Spring Boot Mini Project - Library Management System - Download

Java - Blowfish Encryption and decryption Example

Java - DES Encryption and Decryption example

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete

ReactJS - Bootstrap - Buttons

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Top 5 Java ORM tools - 2024

Java - How to Count the Number of Occurrences of Substring in a String