https://www.w3schools.com/java/java_map.asp
https://www.tutorialspoint.com/java/java_map_interface.htm
https://www.programiz.com/java-programming/map
https://www.geeksforgeeks.org/java/map-interface-in-java/
In Java, the Map Interface is part of the java.util package and represents a collection of key-value pairs, where Keys should be unique, but values can be duplicated.
The Map interface of the Java collections framework provides the functionality of the map data structure.
It provides efficient retrieval, insertion, and deletion operations based on keys.
HashMap and LinkedHashMap allow one null key, and TreeMap does NOT allow null keys (if natural ordering is used).
Use ConcurrentHashMap for thread-safe operations, or Collections.synchronizedMap() to make an existing map synchronized.
The Map interface is a part of the Java Collections Framework and is used to store key-value pairs. Each key must be unique, but values can be duplicated.
In Java, elements of Map are stored in key/value pairs. Keys are unique values associated with individual Values.
A map cannot contain duplicate keys. And, each key is associated with a single value.
The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date.
Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.
Several methods throw a NoSuchElementException when no items exist in the invoking map.
A ClassCastException is thrown when an object is incompatible with the elements in a map.
A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the map.
An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable map.
Access those values using their corresponding keys.
Note: The Map interface maintains 3 different sets:
the set of keys
the set of values
the set of key/value associations (mapping).
Hence we can access keys, values, and associations individually.
We can access and modify values using the keys associated with them.
Common Map Methods
isEmpty() This method is used to check if a map is having any entry for key and value pairs. If no mapping exists, then this returns true.
hashCode() This method is used in Map Interface to generate a hashCode for the given map containing keys and values.
merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) If the specified key is not already associated with a value or is associated with null, associate it with the given non-null value.
put()
Adds or updates a key-value pair
put(K, V) - Inserts the association of a key K and a value V into the map. If the key is already present, the new value replaces the old value.
putAll() - Inserts all the entries from the specified map to this map.
putAll(Map) This method is used in Map Interface in Java to copy all of the mappings from the specified map to this map.
putIfAbsent(K, V) - Inserts the association if the key K is not already associated with the value V.Adds a mapping only if the key is not already mapped.
get()
Returns the value for a given key
get(Object) Returns the value for the given key, or null if not found.
get(K) - Returns the value associated with the specified key K. If the key is not found, it returns null.
getOrDefault(K, defaultValue) - Returns the value associated with the specified key K. If the key is not found, it returns the defaultValue.
getOrDefault(Object key, V defaultValue) Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
remove()
Removes the key and its value.
remove(Object) This method is used in Map Interface to remove the mapping for a key from this map if it is present in the map.
remove(K) - Removes the entry from the map represented by the key K.
remove(K, V) - Removes the entry from the map that has key K associated with value V.
containsKey()
Checks if the map contains the key
containsKey(K) - Checks if the specified key K is present in the map or not.Checks if a key exists in the map.
containsValue(V) - Checks if the specified value V is present in the map or not.Checks if a value exists in the map.
keySet()
Returns a set of all keys
Returns a set of all the keys present in a map.
Returns a set view of the keys in the map.
put(Object, Object) This method is used in Java Map Interface to associate the specified value with the specified key in this map.
values() - Returns a set of all the values present in a map.
Returns a collection view of the map’s values.
entrySet() - Returns a set of all the key/value mapping present in a map.Returns a set view of the map’s key-value pairs.
equals(Object) Compares two maps for equality.
replace(K, V) - Replace the value of the key K with the new specified value V.
replace(K, oldValue, newValue) - Replaces the value of the key K with the new value newValue only if the key K is associated with the value oldValue.
void clear( )
Removes all key/value pairs from the invoking map.
clear() This method is used in Java Map Interface to clear and remove all of the elements or mappings from a specified Map collection.
boolean containsKey(Object k)
Returns true if the invoking map contains k as a key. Otherwise, returns false.
boolean containsValue(Object v)
Returns true if the map contains v as a value. Otherwise, returns false.
Set entrySet( )
Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry. This method provides a set-view of the invoking map.
boolean equals(Object obj)
Returns true if obj is a Map and contains the same entries. Otherwise, returns false.
Object get(Object k)
Returns the value associated with the key k.
int hashCode( )
Returns the hash code for the invoking map.
boolean isEmpty( )
Returns true if the invoking map is empty. Otherwise, returns false.
Set keySet( )
Returns a Set that contains the keys in the invoking map. This method provides a set-view of the keys in the invoking map.
Object put(Object k, Object v)
Puts an entry in the invoking map, overwriting any previous value associated with the key. The key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned.
void putAll(Map m)
Puts all the entries from m into this map.
Object remove(Object k)
Removes the entry whose key equals k.
int size( )
Returns the number of key/value pairs in the map.
size() This method is used to return the number of key/value pairs available in the map.
Collection values( )
Returns a collection containing the values in the map. This method provides a collection-view of the values in the map.
Classes that Implement Map
we cannot create objects from it.
These classes are defined in the collections framework and implemented in the Map interface.
The following are the classes that implement a Map to use the functionalities of a Map -
HashMap
EnumMap
LinkedHashMap
WeakHashMap
TreeMap
Interfaces that Extend Map
The Map interface is also extended by these subinterfaces:
The following are the interfaces that extend the Map interface -
SortedMap
NavigableMap
ConcurrentMap
How to use Map?
In Java, we must import the java.util.Map package in order to use Map. Once we import the package, here's how we can create a map.
// Map implementation using HashMap
Map<Key, Value> numbers = new HashMap<>();
In the above code, we have created a Map named numbers. We have used the HashMap class to implement the Map interface.
Key - a unique identifier used to associate each element (value) in a map
Value - elements associated by keys in a map
Map vs. Set vs. List
Feature:List
Duplicates allowed? Yes
Stores key-value pairs? No
Maintains order? Yes
Feature:Set
Duplicates allowed? No
Stores key-value pairs? No
Maintains order? No (unless using TreeSet or LinkedHashSet)
Feature:Map
Duplicates allowed? Keys: No Values: Yes
Stores key-value pairs? Yes
Maintains order? No (unless using TreeMap or LinkedHashMap)
Declaration of the Map interface
public interface Map<K, V>
K -> Type of keys maintained by the map
V -> Type of mapped values
Creating Map Objects
Since a Map is an interface, we cannot create its object directly. We must use a class that implements it (e.g., HashMap).
Map<String, Integer> hm = new HashMap<>();
import java.util.HashMap;
import java.util.Map;
public class Geeks{
public static void main(String[] args){
// Create a Map using HashMap
Map<String, Integer> m = new HashMap<>();
// Adding key-value pairs to the map
m.put("Geek1", 1);
m.put("Geek2", 2);
m.put("Geek3", 3);
System.out.println("Map elements: " + m);
}
}
Output
Map elements: {Geek3=3, Geek2=2, Geek1=1}
Hierarchy of Map
It is part of the Java Collections Framework, and its key implementation classes include HashMap, LinkedHashMap, TreeMap, and Hashtable.
Note: Map does not extend the Collection interface and is used to efficiently store and retrieve data using keys.
A Map 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 implement Map:
Implemented Classes of Map Interface
Common classes that implement Map:
HashMap: Stores key-value pairs using hashing for fast access, insertion, and deletion.fast and unordered.
LinkedHashMap: Similar to HashMap but maintains the insertion order of key-value pairs.ordered by insertion.
TreeMap: Stores key-value pairs in sorted order using natural ordering or a custom comparator.sorted by key.
Hashtable: A synchronized Map implementation that doesn’t allow null keys or values.
Tip: Use a Map when you want to associate values with unique keys, like storing user IDs with names.
Operations on Map using HashMap
how to perform a few frequently used operations on a Map using the widely used HashMap class.
1. Adding Elements
Use the put() method to add elements to a Map. In HashMap, insertion order isn’t preserved, each element is stored based on its hash for faster access.
import java.util.*;
class Geeks {
public static void main(String[] args) {
// Default initialization of a Map using generics
Map<Integer, String> hm1 = new HashMap<>();
// Initialization of a Map (redundant type on right side unnecessary)
Map<Integer, String> hm2 = new HashMap<>();
// Inserting elements
hm1.put(1, "Geeks");
hm1.put(2, "For");
hm1.put(3, "Geeks");
// Inserting elements — no need to use new Integer()
hm2.put(1, "Geeks");
hm2.put(2, "For");
hm2.put(3, "Geeks");
System.out.println(hm1);
System.out.println(hm2);
}
}
Output
{1=Geeks, 2=For, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}
2. Changing Element
To update a value, use the put() method with the same key. The new value replaces the old one for that key.
import java.util.*;
class Geeks {
public static void main(String args[])
{
// Initialization of a Map using Generics
Map<Integer, String> hm1
= new HashMap<Integer, String>();
// Inserting the Elements
hm1.put(new Integer(1), "Geeks");
hm1.put(new Integer(2), "Geeks");
hm1.put(new Integer(3), "Geeks");
System.out.println("Initial Map: " + hm1);
hm1.put(new Integer(2), "For");
System.out.println("Updated Map: " + hm1);
}
}
Output
Initial Map: {1=Geeks, 2=Geeks, 3=Geeks}
Updated Map: {1=Geeks, 2=For, 3=Geeks}
3. Removing Elements
To remove an element from the Map, we can use the remove() method. This method takes the key value and removes the mapping for a key from this map if it is present in the map.
import java.util.*;
class Geeks{
public static void main(String args[]){
// Initialization of a Map using Generics
Map<Integer, String> hm1
= new HashMap<Integer, String>();
// Inserting the Elements
hm1.put(new Integer(1), "Geeks");
hm1.put(new Integer(2), "For");
hm1.put(new Integer(3), "Geeks");
hm1.put(new Integer(4), "For");
System.out.println(hm1);
hm1.remove(new Integer(4));
System.out.println(hm1);
}
}
Output
{1=Geeks, 2=For, 3=Geeks, 4=For}
{1=Geeks, 2=For, 3=Geeks}
4. Iterating through the Map
There are multiple ways to iterate through the Map. The most famous way is to use a for-each loop and get the keys. The value of the key is found by using the getValue() method.
import java.util.*;
class Geeks{
public static void main(String args[]){
// Initialization of a Map using Generics
Map<Integer, String> hm1
= new HashMap<Integer, String>();
// Inserting the Elements
hm1.put(new Integer(1), "Geeks");
hm1.put(new Integer(2), "For");
hm1.put(new Integer(3), "Geeks");
for (Map.Entry mapElement : hm1.entrySet()) {
int key = (int)mapElement.getKey();
// Finding the value
String value = (String)mapElement.getValue();
System.out.println(key + " : " + value);
}
}
}
Output
1 : Geeks
2 : For
3 : Geeks
Top comments (0)