ProgramGuru

Map Programs

Start with Map Programs

Learn map programs through an executable example, then connect the small demonstration to production code.

What you’ll learn

  • Explain the main purpose of map programs.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Maps associate keys with values and are useful for frequency counting, dictionaries and lookup tables. Iteration order is unspecified, so sort keys when output order matters.

The example counts the occurrences of each fruit and sorts its unique names before printing.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for example mapsA map counts efficiently; a sorted key list controls presentation.Read valuesStep 1Count with mapStep 2Sort keysStep 3Print frequenciesStep 4A map counts efficiently; a sorted key list controls presentation.
A map counts efficiently; a sorted key list controls presentation.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"sort"
)

func main() {
	fruits := []string{"pear", "apple", "pear", "banana", "apple", "pear"}
	counts := make(map[string]int)
	for _, fruit := range fruits {
		counts[fruit]++
	}
	keys := make([]string, 0, len(counts))
	for key := range counts {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	for _, key := range keys {
		fmt.Println(key, counts[key])
	}
}

Output

apple 2
banana 1
pear 3

Trace what the program does

Each encounter increases a zero-default count. Sorting keys gives stable alphabetical output: apple 2, banana 1, pear 3.

Avoid common mistakes

  • Do not depend on map iteration order.
  • Distinguish an absent key from a present key with zero value when the difference matters.

Try it yourself

Change the input words and display only those appearing more than once.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What ensures this map example prints in stable order?
Choose one answer. You can try again.

Answer and explanation

Sorting collected keys

Correct. Each encounter increases a zero-default count.

What you should remember

You have practiced Map Programs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Function Programs →