How to Sort a Map by Values in Go - Step by Step Examples



How to Sort a Map by Values in Go ?

Answer

To sort a map by values in Go, you can convert the map to a slice of key-value pairs, sort the slice by values, and then iterate over the sorted slice to access the key-value pairs. This method allows you to sort the map based on values.



✐ Examples

1 Sorting a Map by Values Using a Slice of Pairs

We can sort a map by values in Go by converting the map to a slice of key-value pairs, sorting the slice by values, and then iterating over the sorted slice to access the key-value pairs.

For example,

  1. We start by importing the fmt and sort packages, which provide the necessary functions for input-output operations and sorting.
  2. We declare and initialize a map named myMap with some key-value pairs. In this example, the map has string keys and integer values.
  3. We create a slice of key-value pairs named kv and copy the key-value pairs from the map to the slice.
  4. We sort the slice by values using the sort.Slice function with a custom comparator.
  5. We iterate over the sorted slice and print the key-value pairs in sorted order using the fmt.Println function.

Go Program

package main

import (
    "fmt"
    "sort"
)

func main() {
    // Declare and initialize a map
    myMap := map[string]int{
        "apple": 3,
        "banana": 1,
        "cherry": 2,
    }

    // Create a slice of key-value pairs
    kv := make([]struct{
        Key   string
        Value int
    }, 0, len(myMap))

    for k, v := range myMap {
        kv = append(kv, struct{
            Key   string
            Value int
        }{k, v})
    }

    // Sort the slice by values
    sort.Slice(kv, func(i, j int) bool {
        return kv[i].Value < kv[j].Value
    })

    // Print the sorted key-value pairs
    fmt.Println("Sorted Map by Values:")
    for _, kv := range kv {
        fmt.Printf("%s: %d\n", kv.Key, kv.Value)
    }
}

Output

Sorted Map by Values:
banana: 1
cherry: 2
apple: 3

2 Sorting a Map by Values in Descending Order

We can sort a map by values in descending order in Go by converting the map to a slice of key-value pairs, sorting the slice by values in descending order, and then iterating over the sorted slice to access the key-value pairs.

For example,

  1. We start by importing the fmt and sort packages, which provide the necessary functions for input-output operations and sorting.
  2. We declare and initialize a map named myMap with some key-value pairs. In this example, the map has string keys and integer values.
  3. We create a slice of key-value pairs named kv and copy the key-value pairs from the map to the slice.
  4. We sort the slice by values in descending order using the sort.Slice function with a custom comparator.
  5. We iterate over the sorted slice and print the key-value pairs in sorted order using the fmt.Println function.

Go Program

package main

import (
    "fmt"
    "sort"
)

func main() {
    // Declare and initialize a map
    myMap := map[string]int{
        "apple": 3,
        "banana": 1,
        "cherry": 2,
    }

    // Create a slice of key-value pairs
    kv := make([]struct{
        Key   string
        Value int
    }, 0, len(myMap))

    for k, v := range myMap {
        kv = append(kv, struct{
            Key   string
            Value int
        }{k, v})
    }

    // Sort the slice by values in descending order
    sort.Slice(kv, func(i, j int) bool {
        return kv[i].Value > kv[j].Value
    })

    // Print the sorted key-value pairs
    fmt.Println("Sorted Map by Values (Descending):")
    for _, kv := range kv {
        fmt.Printf("%s: %d\n", kv.Key, kv.Value)
    }
}

Output

Sorted Map by Values (Descending):
apple: 3
cherry: 2
banana: 1

3 Sorting a Map with Numeric Keys by Values

We can sort a map with numeric keys by values in Go by converting the map to a slice of key-value pairs, sorting the slice by values, and then iterating over the sorted slice to access the key-value pairs.

For example,

  1. We start by importing the fmt and sort packages, which provide the necessary functions for input-output operations and sorting.
  2. We declare and initialize a map named myMap with some key-value pairs. In this example, the map has integer keys and string values.
  3. We create a slice of key-value pairs named kv and copy the key-value pairs from the map to the slice.
  4. We sort the slice by values using the sort.Slice function with a custom comparator.
  5. We iterate over the sorted slice and print the key-value pairs in sorted order using the fmt.Println function.

Go Program

package main

import (
    "fmt"
    "sort"
)

func main() {
    // Declare and initialize a map
    myMap := map[int]string{
        3: "three",
        1: "one",
        2: "two",
    }

    // Create a slice of key-value pairs
    kv := make([]struct{
        Key   int
        Value string
    }, 0, len(myMap))

    for k, v := range myMap {
        kv = append(kv, struct{
            Key   int
            Value string
        }{k, v})
    }

    // Sort the slice by values
    sort.Slice(kv, func(i, j int) bool {
        return kv[i].Value < kv[j].Value
    })

    // Print the sorted key-value pairs
    fmt.Println("Sorted Map by Values:")
    for _, kv := range kv {
        fmt.Printf("%d: %s\n", kv.Key, kv.Value)
    }
}

Output

Sorted Map by Values:
1: one
2: two
3: three

Summary

In this tutorial, we learned How to Sort a Map by Values in Go language with well detailed examples.




More Go Maps Tutorials

  1. How to create an Empty Map in Go ?
  2. How to create a Map with Initial Key-Value Pairs in Go ?
  3. How to Print a Map in Go ?
  4. How to Add a Key-Value Pair to a Map in Go ?
  5. How to Set a Default Value for a Key in a Map in Go ?
  6. How to Update the Value for a Key in a Map in Go ?
  7. How to Check if a Map is Empty in Go ?
  8. How to Check if a Key Exists in a Map in Go ?
  9. How to Check if a Value Exists in a Map in Go ?
  10. How to Get the Value Associated with a Key in a Map in Go ?
  11. How to Remove a Key-Value Pair from a Map in Go ?
  12. How to Remove Key-Value Pairs from a Map Based on Values in Go ?
  13. How to Clear All Key-Value Pairs from a Map in Go ?
  14. How to Iterate Over Keys in a Map in Go ?
  15. How to Iterate Over Values in a Map in Go ?
  16. How to Iterate Over Entries (Key-Value Pairs) in a Map in Go ?
  17. How to Get the Size (Number of Key-Value Pairs) of a Map in Go ?
  18. How to Convert a Map to an Array of Keys in Go ?
  19. How to Convert a Map to an Array of Values in Go ?
  20. How to Convert a Map to an Array of Key-Value Pairs in Go ?
  21. How to Merge Two Maps in Go ?
  22. How to Copy a Map in Go ?
  23. How to Check if Two Maps are Equal in Go ?
  24. How to Sort a Map by Keys in Go ?
  25. How to Sort a Map by Values in Go ?
  26. How to Filter a Map Based on Keys in Go ?
  27. How to Filter a Map Based on Values in Go ?
  28. How to Reduce Values in a Map to a Single Value in Go ?
  29. How to Convert an Array of Key-Value Pairs to a Map in Go ?
  30. How to Convert a Map to a JSON String in Go ?
  31. How to Convert a JSON String to a Map in Go ?
  32. How to Swap Keys and Values in a Map in Go ?
  33. How to Create a Map of Maps in Go ?
  34. How to Iterate Over a Map of Maps in Go ?