How to iterate over a map in Go?

A map is an unordered collection of key/value pairs, where each key is unique. Go Range keyword is used in different kinds of data structures in order to iterate over elements.

Example 1: Iterate over all keys and values

// Go program to illustrate how
// to iterate the map
package main

import "fmt"

// Main function
func main() {

// Let’s define a map first
usermap := map[string]string{

"North America": "Adam",
"Asia": "Yusuke",
"Africa": "Arif",
"South America": "Rahul",
"Australia": "Joy",
"Europe": "Roman",
"Antarctica": "Penguin",
}

// Iterating over all keys and values
for id, name := range usermap {

fmt.Printf("id :%s name: %s\n", id, name)
}
}

Output:



Example 2: Iterate over all keys

// Go program to illustrate how
// to iterate the map
package main

import "fmt"

// Main function
func main() {

// Let’s define a map first
usermap := map[string]string{

"North America": "Adam",
"Asia": "Yusuke",
"Africa": "Arif",
"South America": "Rahul",
"Australia": "Joy",
"Europe": "Roman",
"Antarctica": "Penguin",
}

// Iterating over all keys
for id := range usermap {

fmt.Printf("id :%s\n", id)
}
}

Output:



Example 3: Iterate over all values

// Go program to illustrate how
// to iterate the map
package main

import "fmt"

// Main function
func main() {

// Let’s define a map first
usermap := map[string]string{

"North America": "Adam",
"Asia": "Yusuke",
"Africa": "Arif",
"South America": "Rahul",
"Australia": "Joy",
"Europe": "Roman",
"Antarctica": "Penguin",
}

// Iterating over all values
for _, name := range usermap {

fmt.Printf("name :%s\n", name)
}
}

Output:

                                            
                                        Author name,
                                                                                Seril

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