Java: Map Interface
Map interface provides the mapping of key and value. Map contains a unique key which mapped to at most one value.
- Creating objects with Map:
Map<Integer, String> map = new HashMap<Integer, String>();Implementations of Map interface:
- HashMap:
HashMap class extends Map interface. It stores the value in form of key-value pair, and you can access the values by using the keys. It does not allow duplicate keys. If we try to insert, then it will replace the existing value corresponding to that key. It is the same as HashTable, but it is not synchronized.
HashMap can be synchronized by calling:
Map map = Collections.synchronizedMap(hashMap);In HashTable, Key is hashed using hashCode() and then resulting hash value is used as index to retrieve value stored at the index in HashTable.
- Difference between HashMap and HashTable:
2. LinkedHashMap:
Get Shradha Yewale’s stories in your inbox
Join Medium for free to get updates from this writer.
LinkedHashMap extends the HashMap class and it maintains the order in which elements are inserted. It is the same as HashMap but HashMap does not maintain the order of elements.
HashMap is quicker than LinkedHashMap for insertion, retrieval, and search of elements.
LinkedHashMap<Integer, String> linkedMap = new LinkedHashMap<Integer, String>();3. TreeMap:
TreeMap implements the NavigableMap interface and extends AbstractMap class. TreeMap is sorted according to the natural ordering(ascending) of its keys. It uses Comparator at the time of map creation to sort and store key-value pairs. TreeMap is not synchronized. If multiple threads are accessing it then it must be synchronized externally.
TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();- Code implementation
Applications of Maps:
- To map classes to students. Class(Key) -> Students(list of values)
- To map manager and employees.
- To map States to cities.










