This is an Introduction to Java Collections Map Interface. We will learn what are the important features of Map types and when should you use Map implementations.
Tutorial Contents
Introduction to Maps
Map is an Interface in java.utils
package. Map is an important Java Collection. However, it doesn’t implement Java Collection interface. All other collections in Java, except Map, implement this interface. However, the Map is still considered as a java Collection.
The Map collections store objects in the form of Keys and Values. The Set interface in java only allows unique elements. Similarly, the Map allow unique keys. The key and value pair represent an entry the Map. The Map makes use of Hash Table algorithm to store the entries.
When you push a key value pair (entry) to a map, the Map finds hashCode. Map uses this hashCode to find an associated bucket. It then stores the entry into the bucket.Multiple entry object can be present in the same bucket and this is called as Hash Collision. In other words, different keys producing same hashCode are stored in the same bucket.
When you try to retrieve a value from Map, you pass the respective key. Again, the hashCode of the key helps locating the bucket. Map then does the equality check with the key and key from each of the entries in the bucket to return respective value.
Baceause of this the normal put, get, contains etc operations are constant in time. Map takes same amount of time to put or get an object no matter how many elements are present in the Map.
Features of Map
- Map is a key/value store. Where, a key is an handle to the value.
- Maps are similar to Set. However, in Map the hashing is done on the key and not a value.
- You can’t have duplicate keys in Map. However, you can duplicate values any number of times.
- Maps allow one and only one null keys.
- The entries in Map are not sorted, not ordered by default. However, some implementations of Map support this.
- Maps are not synchronised. In other words multiple threads can act as the same time on map.
- However if you try to modify a Map once an iterator is open you get
ConcurrentModificationException
. This behavior of an Iterator is called as fail fast. Because, if there are synchronisation issues, the iterator simply fails instead of returning dirty values. - The map performs get, put, contains like operations constant in time irrespective of the Map size.
- Being a key/value storage it is best to store in-memory properties of configurations or even generically hold an object state.
Immutable Maps
Immutable Maps are unmodifiable after creation. in other words, when you create an Immutable Map, you cannot add, remove, or modify any entry from the Map. You may use immutable maps thread safely in any environments. If you try to modify an immutable map you get UnsupportedOperationException
.
Java 9 Provides, factory methods to create Immutable maps inline.
// Created Empty Immutable HashMap using Java 9 factory methods
Map<String, String> map = Map.of();
System.out.println(map.size()) // output : 0
map.put("1", "2");
// Output
// Exception java.lang.UnsupportedOperationException
// at ImmutableCollections.uoe (ImmutableCollections.java:71)
// at ImmutableCollections$AbstractImmutableMap.put (ImmutableCollections.java:714)
// at (#3:1)
Code language: Java (java)
In this example, we got an exception. Which indicates factory methods created an Immutable Map.
Map Store Unique Keys
As discussed earlier, a Map doesn’t allow duplicating key object. However, you can duplicate a value any number of times.
Map<String, String> map = new HashMap<>();
map.put("key_1", "value_1");
map.put("key_2", "value_1");
map.put("key_1", "value_2");
map.put(null, null);
Code language: Java (java)
Firstly, we added key_1 and then added key_2 with same (duplicate) value. After that, we duplicated the key_1 with different value. Also, we added a null key and null value. After this, we print the map and see the below outcome.
{null=null, key_2=value_1, key_1=value_2}
Code language: plaintext (plaintext)
The map has accepted null as both key and value. However, it only allows one null key. Also, the value of key_1 is replaced to value_2. Hence, we saw Maps do not allow duplicate keys. If you try to put a duplicate key the the map will replace the entry with new value.
- How to Initialize a HashMap Inline in Java
- Convert List of Strings to Concatenated String with Delimiter in Java
- Introduction to Java LinkedHashSet With Examples
- Examples of Converting List to Map using Streams
- How to Initialize a HashSet Inline in Java
- Introduction to HashMap in Java with Examples
- Introduction to Java TreeSets With Examples
Add Entries in Map
Below are few basic methods to add elements to Map:
- put(K key, V value): Adds the key given key, value pair to the map. If the key is is found already in the collection, the map will replace it with the new value and the old value will be returned.
- putAll(Map<? extends K, ? extends V> m): It copies all the entries from the given map to the target map.
- putIfAbsent(K key, V value): Checks if the given key is present. If present, returns the existing value and does nothing. If absent, it will store the new entry and return null.
Remove Entries from Map
- remove(Object key): Finds and removes an entry with given key. Return the current value before removal.
- remove(Object key, Object value): Removes the entry only if the given key has given value in the collection.
- replace(K key, V value): Replaces the value of given key with given value. Note: replace happens only if the key is present in the collection.
- replace(K key, V oldValue, V newValue): It will replace the value only if the given key has given old value.
- replaceAll(BiFunction<? super K, ? super V, ? extends V> function): It applies the given function on all the entries of the collection. BiFunction is a type of Functional Interface in Java.
Summary
You are at the end of this short Introduction to Java Collections Map Interface. To sum up, you learnt Map is an interface and considered to be part of Java Collections API. The maps store key value pairs where they hash the keys. Hence you cannot put duplicate keys into Map. Also, you can only add one null key.
In the Maps, the operations like put, get, contains are constant in time and irrespective of the size of the Map. Maps are not synchronised but the iterators on the Map are fail fast. However, you can synchronise the objects accessing the map concurrently.