Map in Java
Map associates each key with a value. A key has at most one mapping at a time, while several different keys may have equal values. Map is part of the Collections Framework, but it does not extend the Collection interface.
Why Do We Need This?
A learner ID can act as a key for finding a learner name. We can look up the name using that ID instead of scanning a list and comparing every learner.
Main Ideas
| Concept | What it means |
|---|---|
| put(key, value) | Adds a mapping or replaces the value for an existing key |
| get(key) | Reads the mapped value, or returns null if none is found |
| containsKey(key) | Checks whether a key has a mapping |
| HashMap | Does not promise an iteration order |
| LinkedHashMap and TreeMap | Provide insertion/access ordering or sorted key ordering |
Simple Working Example
Run this program on its own. All required imports and classes are included.
import java.util.LinkedHashMap;
import java.util.Map;
public class HelloWorld {
public static void main(String[] args) {
Map<Integer, String> learners = new LinkedHashMap<>();
learners.put(101, "Meera");
learners.put(102, "Kabir");
learners.put(101, "Tara");
System.out.println(learners);
System.out.println("Learner 101: " + learners.get(101));
System.out.println("Mappings: " + learners.size());
}
}Output
{101=Tara, 102=Kabir}
Learner 101: Tara
Mappings: 2Putting another value for key 101 replaces its earlier value. LinkedHashMap keeps the insertion order in this example. For a map that allows null values, get returning null alone cannot distinguish a missing key from a key mapped to null.
Topics in This Section
Easy Way to Remember
Choose a map when values are found by keys. Keep fields used for key equality or ordering stable while the key is stored.
See you in next page....??