Jump to content

Sort a Map in Go by Value (Sort Map by Value)


Linux Hint

Recommended Posts

Data structures are some of the most versatile and powerful features in any programming language that actually support them.

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:

map := make(map[string]int)

We can also use the composite literal to define a map with elements as demonstrated in the following example:

map := map[string]int{
    "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["a"] = 100
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:

fmt.Println(map["b"])

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.

delete(map, "a")

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.

value, exists := map["a"]
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.

for key, value := range 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:

package main

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.

MySQL 3306
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.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...