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:

Popular posts from this blog

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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

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

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

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