One of the most common and powerful data structures in the Go programming language is a map. Map data structure allows us to store the key-value pairs, providing an efficient way of associating the values with unique keys.
This makes maps important and play a crucial role in the heart of many Go applications including microservices, multithreading, and more.
By default, maps in Go are unordered which means that they do not contain a specific order for the key-value combinations. This can be a hindrance especially when in instances where the order is important.
In this guide, we will explore the various methods and techniques that you can use to sort a map by its values.
The Basics
As we mentioned, a map in Go is a built-in data structure that stores a collection of key-value pairs. Each key in a map must be unique and is used to identify as well as manipulate the value associated with it.
You may hear maps referred to associative arrays, dictionaries, or hash tables in other programming languages. This is because they are the basis of these data structures and share a lot.
Map Initialization in Go
In Go, we can create an empty map using the “make” method. For example, the following code shows how to create an empty map with keys and values of string and int types, respectively:
We can also use the composite literal to define a map with elements as demonstrated in the following example:
"a": 100,
"b": 455,
"b": 402,
}
Adding the Key-Value Pairs
Once we create a map, we can add the key-value pairs into it using the square bracket notation as demonstrated in the following example:
map["b"] = 455
map["c"] = 402
In this case, we add three key-value pairs into the map.
Accessing the Values
We can access the values of a map by referencing their corresponding keys. For example, use the following command to reference the second element in the map:
This should return the corresponding value whose key is the letter “b”.
Deleting the Values
To remove a key-value pair from a map, we can use the “delete” function and provide the key that we wish to remove.
The given code removes the key of “a” and its associated value.
Checking the Key Existence
We can check if a key exists in a map using a two-value assignment. The second value is a Boolean that indicates whether the key exists in the map.
if exists {
fmt.Println("The key a exists with value", value)
} else {
fmt.Println("The key "a" does not exist.")
}
The code should print the appropriate message if the key exists or does not exist in the specified map.
Map Iteration
Map iteration is a common task in Go and other languages. Luckily, we can use a basic “for” loop in Go to iterate over the key-value pairs of a map.
fmt.Println(key, value)
}
This should return the key and value pair in the map.
Sort a Map in Go by Value
Let us now explore the various methods and techniques that we can use to sort a map by its value.
Method: Slice of Structs
One of the most common techniques of sorting a map by the value is converting the map into a slice of structs. Each struct contains a key and a value.
We can then sort the slice based on the values and iterate over the sorted slice to access the pairs in sorted order.
Take the following example that demonstrates how to do this:
import (
"fmt"
"sort"
)
func main() {
db := map[string]int{
"MySQL": 3306,
"Redis": 6379,
"MongoDB": 27017,
}
type KeyValue struct {
Key string
Value int
}
// Convert the map to a slice of KeyValue structs
var keyValueSlice []KeyValue
for key, value := range db {
keyValueSlice = append(keyValueSlice, KeyValue{key, value})
}
// Sort the slice by value in ascending order
sort.Slice(keyValueSlice, func(i, j int) bool {
return keyValueSlice[i].Value < keyValueSlice[j].Value
})
// Iterate over the sorted slice and print key-value pairs
for _, kv := range keyValueSlice {
fmt.Println(kv.Key, kv.Value)
}
}
In the given example, we start by converting the map to a slice of “KeyValue” structs. We do this using a “for” loop and extract the key and value from the slice using range.
In the next step, we proceed to use the sort.Slice() function to sort the “keyValueSlice” based on the “Value” field of the struct.
Once we sort the slice by value, we can basically use an iterator to access the key-value pairs in the sorted order.
Redis 6379
MongoDB 27017
Conclusion
In this tutorial, we covered the fundamentals of working with maps in Golang. We also learned how to use structs to sort a map by value and by keys.