Key-value pairs for lookup
Day 136 of 149
π Full deep-dive with code examples
The Phone Book Analogy
Remember phone books?
- Find "Smith" β Flip directly to S section
- Look up the name β Get the phone number
- You don't scan from the beginning!
Maps work like phone books!
You look up a "key" (name) and instantly get a "value" (phone number).
The Problem They Solve
Looking up things in a list is slow:
- 1 million items?
- Check one by one?
- That could take forever!
With a map:
- Store key β value pairs
- Look up by key
- Get the answer instantly!
How Maps Work
Maps store pairs of things:
Key β Value
"name" β "Alice"
"age" β 30
"city" β "Sydney"
To get a value, just use the key:
- Ask for "name" β Get "Alice"
- Ask for "age" β Get 30
No searching through everything!
Why They're Fast
Behind the scenes, maps use a smart trick:
- Convert the key to a number (hashing)
- Use that number to find the exact location
- Go directly there
Like a library catalog card telling you exactly which shelf.
Common Uses
- User profiles β ID β user data
- Configuration β setting name β value
- Counting things β item β count
- Caching β query β result
Map vs Array
| Array | Map |
|---|---|
| Access by position (0, 1, 2...) | Access by key ("name", "age") |
| Good for ordered lists | Good for lookups |
| Find item: slow (scan) | Find item: instant |
In One Sentence
Maps store key-value pairs so you can instantly look up any value by its key, like finding a phone number by name.
π Enjoying these? Follow for daily ELI5 explanations!
Making complex tech concepts simple, one day at a time.
Top comments (0)