Map Basics
A Map is one of the most important collections in Java โ especially for web development.
Itโs a special key-value store, meaning:
Every key is unique.
Each key maps to one specific value.
You can use the key to quickly find or update the value.
You can think of a Map
like a real-world dictionary:
The word is the key.
The definition is the value.
If you know the word, you instantly get the definition.
Why is a Map so useful in web development?
Handling form data: When a user submits a form, the server often stores fields in a Map<String, String>
โ keys are field names, values are user input.
Request parameters: Query strings and path variables are easily stored as maps.
Session data: Many frameworks use Map
to hold user session information.
JSON objects: When you parse JSON, the internal structure often maps naturally to a Map
.
Headers: HTTP request/response headers are key-value pairs โ perfect for a map.
Most common implementation:
HashMap
โ general purpose, very fast lookups.
LinkedHashMap
โ keeps insertion order.
TreeMap
โ keeps keys sorted.
For most tasks, HashMap
is the go-to choice.
When using a Map
, you usually do 4 main things:
- Add or update:
Use put(key, value)
to add a new key-value pair or update an existing one.
- Retrieve:
Use get(key)
to find the value for a given key.
If the key doesnโt exist, it returns null
.
- Remove:
Use remove(key)
to delete a key and its value.
- Loop:
You can loop over:
Keys: keySet()
Values: values()
Entries: entrySet()
โ each entry holds a key + its value.
Mini Lab: Using HashMap in Practice
Below is a practical example that shows all four core operations.
Key points in this Mini Lab:
put()
works for both adding and updating โ if the key exists, its value changes.
get()
lets you pull out any value in constant time, no looping needed.
remove()
deletes both the key and the value at once.
keySet()
gives you all the keys.
entrySet()
is great when you need both keys and values at the same time.
HashMap
uses a hash table under the hood, so operations are very fast, even with lots of data.
In real-world web backends, Map
is everywhere:
REST APIs: When you parse or build JSON objects, you often store them in a Map<String, Object>
.
Configuration: App settings are usually stored in Map
structures so you can look up values by key.
Caching: Many caching solutions keep session data or database query results in a Map
for fast reuse.
Spring Boot: Request parameters (@RequestParam
), model attributes (ModelMap
), and environment variables often rely on Map
.