Map Collection

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Map

- Map is a Interface which is part of the java collection.


- Map interface represents a mapping between Keys and Values.
- Major Implemetnion of Map interfaces are HashMap, TreeMap and LinkedHashMap.

HashMap TreeMap LinkedHashMap


Null Key 1 Null allowed No Null Key 1 Null Key allowed
Allowed(NullPointerException)
Null Value Multiple allowed Multiple Allowed Multiple Allowed
Insertion Order Not Maintained Ascending order Insertion order
preserved
Duplicate Key Not Allowed Not Allowed Not Allowed
Duplicate Values Allowed Allowed Allowed

HashMap:
HashMap<KeyType, ValueType> hashMap = new HashMap< KeyType, ValueType >();

TreeMap:
TreeMap<KeyType, ValueType> treeMap = new TreeMap< KeyType, ValueType >();
Replace KeyType with the desired key type, and ValueType with the desired value type.
LinkedHashMap:
LinkedHashMap<KeyType, ValueType> linkedHashMap = new LinkedHashMap< KeyType,
ValueType >();
Replace KeyType with the desired key type, and ValueType with the desired value type. For
example, you can use String as the key type and Integer as the value type.
# All The Methods:

Here are some common methods available in all three implementations:

1. put(key, value): Inserts a key-value pair into the map.


2. get(key): Retrieves the value associated with a given key.
3. containsKey(key): Checks if a key is present in the map.
4. containsValue(value): Checks if a value is present in the map.
5. remove(key): Removes a key-value pair from the map based on the given key.
6. size(): Returns the number of key-value pairs in the map.
7. isEmpty(): Checks if the map is empty.
8. keySet(): Returns a set containing all the keys in the map.
9. values(): Returns a collection containing all the values in the map.
10. entrySet(): Returns a set containing all the key-value pairs in the map as entries.

However, each implementation also has some unique characteristics and additional methods:

 HashMap: Provides constant-time performance for basic operations (such as put, get, and remove) on
average. It does not guarantee any particular order for the elements.
 TreeMap: Maintains the keys in sorted order, either using the natural order of the keys or a custom
Comparator. It provides efficient operations for finding ranges and retrieving entries based on their
order.
 LinkedHashMap: Maintains the order of elements based on the insertion order or access order (by
setting accessOrder to true in the constructor). It offers predictable iteration order.

You might also like