Working with Maps and Sorting in Go

This lesson's topic is working with Maps and Sorting in Go. Learning to access map data in order enriches our toolkit for organized and efficient data manipulation.

Using Maps and the sort Package

Go's sort package helps us access map data in a sorted fashion. To illustrate, we create a map and use slices to sort keys, allowing us to display map values in order.

One approach we can take is to extract all keys int a slice, sort this slice, and print the values in a natural order (alphabetically). Here's an example:

package main

import (
    "fmt"
    "sort"
)

func main() {
    // Map with fruits as keys and corresponding counts as values
    fruitCounts := map[string]int{
        "banana": 3,
        "apple":  4,
        "pear":   1,
        "orange": 2,
    }

    // Extract and sort keys
    keys := make([]string, 0, len(fruitCounts))
    for key := range fruitCounts {
        keys = append(keys, key)
    }
    sort.Strings(keys)

    // Print fruits in sorted order by keys
    for _, key := range keys {
        fmt.Printf("%s=%d\n", key, fruitCounts[key])
    }
}

The output will be:

apple=4
banana=3
orange=2
pear=1
Operations with Sorted Access

Using slices to sort keys, we can implement functionalities for map operations like existence checks and removals, accessing elements in a sorted order:

package main

import (
    "fmt"
    "sort"
)

func main() {
    // Initialize the map
    fruitCounts := map[string]int{
        "banana": 3,
        "apple":  4,
        "pear":   1,
        "orange": 2,
    }

    // Check existence
    if _, exists := fruitCounts["apple"]; exists {
        fmt.Println("Contains 'apple' key: True")
    }

    // Remove an element
    delete(fruitCounts, "apple")
    if _, exists := fruitCounts["apple"]; !exists {
        fmt.Println("Removed 'apple': True") // Output: True
    }

    // Fetch non-existent key
    value, exists := fruitCounts["apple"]
    if !exists {
        fmt.Println("Value: Not found") // Output: Value: Not found
    } else {
        fmt.Printf("Value: %d\n", value)
    }

    // Find and display the last element in sorted key order
    keys := make([]string, 0, len(fruitCounts))
    for key := range fruitCounts {
        keys = append(keys, key)
    }
    sort.Strings(keys)
    lastKey := keys[len(keys)-1]
    fmt.Printf("Last entry: %s=%d\n", lastKey, fruitCounts[lastKey]) // Output: pear=1
}
Lesson Summary

You've explored how to sort access in Go using regular maps. This included extracting and sorting keys with the sort package to access map values in order, and performing essential operations. Continue practicing to deepen your understanding of maps and sorting in Go.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal