JavaMap
Java Map Interface
TheMap interface is a part of theJava Collections Framework and is used to storekey-value pairs. Each key must be unique, but values can be duplicated.
AMap is useful when you want to associate a key (like a name or ID) with a value (like an age or description).
Common classes that implementMap:
HashMap- fast and unorderedTreeMap- sorted by keyLinkedHashMap- ordered by insertion
Tip: Use aMap when you want to associate values with unique keys, like storing user IDs with names.
Common Map Methods
| Method | Description |
|---|---|
put() | Adds or updates a key-value pair |
get() | Returns the value for a given key |
remove() | Removes the key and its value |
containsKey() | Checks if the map contains the key |
keySet() | Returns a set of all keys |
Map vs. Set vs. List
| Feature | List | Set | Map |
|---|---|---|---|
| Duplicates allowed? | Yes | No | Keys: No Values: Yes |
| Stores key-value pairs? | No | No | Yes |
| Maintains order? | Yes | No (unless using TreeSet or LinkedHashSet) | No (unless using TreeMap or LinkedHashMap) |
Next, we'll look at how to useHashMap to store items in key/value pairs.

