Java Map Interface

In this tutorial, we will learn about the java.util.Map interface, how to use, its behaviour, methods, use cases along with working examples of Map interface.

java.util.Map interface

The java.util.Map interface in Java used to store key-value pairs in a collection which is a part of the collections framework and provides a convenient way to access, store, and manipulate elements based on keys.

The Map interface is implemented by several classes such as HashMap, TreeMap, LinkedHashMap, etc.

In this discussion, we will explore the methods of the Map interface, understand its usage with the working examples, and discuss its use cases.

The Map interface represents a collection of key-value pairs, where each key is unique and associated with a corresponding value.

The Map interface provides methods for adding, removing, and searching for keys and values, as well as operations for iterating over the map and performing operations on multiple keys and values.

Map interface methods

Here is a table summarizing the methods declared in the Map interface:

MethodDescription
void clear()Removes all the mappings from this map.
boolean containsKey(Object key)Returns true if this map contains a mapping for the specified key.
boolean containsValue(Object value)Returns true if this map, maps one or more keys to the specified value.
Set<Map.Entry<K, V>> entrySet()Returns a Set view of the mappings contained in this map.
boolean equals(Object o)Checks the specified object with this map for equality.
V get(Object key)Returns the value to which the specified key is mapped otherwise null if this map does not contain any mapping for the key.
boolean isEmpty()Returns true if this map contains no key-value mappings.
Set<K> keySet()Returns a Set view of the keys contained in this map.
V put(K key, V value)Creates a mapping of specified value with the specified key in this map.
void putAll(Map<? extends K,? extends V> m)Copies all the mappings from the specified map to this map.
V remove(Object key)Removes the mapping for a key from this map if it is present.
int size()Returns the number of key-value mappings in this map.
Collection<V> values()Returns a Collection view of the values contained in this map.

java.util.Map example with in-built class object:

In the following example, we will add fruits as keys and value as its prices and iterate over it keys.

CopiedCopy Code
import java.util.HashMap;
import java.util.Map;
public class MapExample {
    public static void main(String[] args) {
        Map<String, Integer> fruitPrice = new HashMap<>();
        fruitPrice.put("Apple", 100);
        fruitPrice.put("Muskmelon", 80);
        fruitPrice.put("Mango", 150);
        System.out.println("Apple price is $"+fruitPrice.get("Apple")); // Output: 100
        fruitPrice.remove("Muskmelon");
        for (String name : fruitPrice.keySet()) {
            System.out.println(name + " is $" + fruitPrice.get(name));
        }
    }
}

Output:

Apple price is $100
Apple is $100
Mango is $150

Explanation:

In this example, we create a HashMap that maps fruits to price. Then we added three fruits to the map using the put method. We retrieve the price of Apple using the get method and printed it to the console.

We then removed the entry for Muskmelon using the remove method.

We loop over the keys in the map using the keySet method and output each fruit name and price printed it to the console.

java.util.Map example with custom class object:

In this example, we will use custom class key by overriding the hashCode() and equals() methods.

CopiedCopy Code
import java.util.HashMap;
import java.util.Map;
public class MapExampleCustomKey {
	public static void main(String[] args) {
		Map<CustomKey,String> weather = new HashMap();
		CustomKey key = new CustomKey("India");
		CustomKey key1 = new CustomKey("US");
		CustomKey key2 = new CustomKey("UK");
		CustomKey key3 = new CustomKey("India");
		weather.put(key, "Moderate Temperature");
		weather.put(key1, "Suitable for outing");
		weather.put(key2, "Extreme Cold");
		//Will replace the value of key India with new value
		weather.put(key3, "About to Rain");
		System.out.println(weather);
	}
	static class CustomKey {
		public String location;
		public CustomKey(String location) {
			this.location = location;
		}
		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + ((location == null) ? 0 : location.hashCode());
			return result;
		}
		@Override
		public boolean equals(Object obj) {
			CustomKey other = (CustomKey) obj;
			if (location.equals(other.location))
				return true;
			return false;
		}
		@Override
		public String toString() {
			return "location:" + location;
		}
	}
}

Output:

{location:UK=Extreme Cold, location:US=Suitable for outing, location:India=About to Rain}

Use Cases:

The Map is widely used by the software developers for various purposes, the following are few use cases.

  1. Database lookups.
  2. Data Caching, helps to improve the performance
  3. Data storage and retrieval.

Conclusion:

In this tutorial, we have explored on java.util.Map interface, methods of it and use cases along with a working example of Map including with the custom key by overriding equals and hashCode methods.