Data Aggregation Techniques Using Maps in Go

Topic Overview

Greetings, learners! Today's focus is data aggregation, a practical concept featuring maps as our principal tool in Go.

Data aggregation refers to gathering "raw" data and subsequently presenting it in an analysis-friendly format. A helpful analogy is viewing a cityscape from an airplane, which provides an informative aerial overview rather than delving into the specifics of individual buildings. We'll demonstrate how to manually perform operations like summation, counting, maximum, minimum, and averaging using loops and map iterations in Go.

Let's dive in!

Understand Aggregation

Data aggregation serves as an effective cornerstone of data analysis, enabling data synthesis and presentation in a more manageable and summarized format. Imagine identifying the total number of apples in a basket at a glance, instead of counting each apple individually. With Go, we can achieve this by manually iterating over map entries to aggregate data.

Data Aggregation Using Maps

Let's unveil how maps assist us in data aggregation. Picture a Go map wherein the keys signify different fruit types, and the values reflect their respective quantities. A map can efficiently hold and help aggregate these quantities through various operations like summation, counting, max, min, and average, all performed manually using loops.

Summing Values in a Map

Let's delve into a hands-on example using a fruit basket represented as a map. In Go, we manually iterate over the map to find the sum of items:

package main

import "fmt"

func main() {
    // A map representing our fruit basket
    fruitBasket := map[string]int{
        "apples":  5,
        "bananas": 4,
        "oranges": 8,
    }

    // Summing the values in the map
    totalFruits := 0
    for _, quantity := range fruitBasket {
        totalFruits += quantity
    }

    fmt.Println("The total number of fruits in the basket is:", totalFruits)
    // It outputs: "The total number of fruits in the basket is: 17"
}

Counting Elements in a Map

Just as easily, we can count the number of fruit types in our basket, which corresponds to the number of keys in our map using the len() function.

package main

import "fmt"

func main() {
    // A map representing our fruit basket
    fruitBasket := map[string]int{
        "apples":  5,
        "bananas": 4,
        "oranges": 8,
    }

    // Counting the elements in the map
    countFruits := len(fruitBasket)
    fmt.Println("The number of fruit types in the basket is:", countFruits)
    // It outputs: "The number of fruit types in the basket is: 3"
}
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