Java Map Interface
Introduction to Java Map Interface
The Java Map Interface is part of the Java Collections Framework. It provides a structure that allows mapping unique keys to values. This concept can be assimilated to a real-world map where you look for a location (the key) to find a specific point (the value). In the Java Map Interface, keys are unique. This means that you can only map one value with a specific key.
Understanding the Java Map Interface
The Java Map Interface is part of the java.util package. It is not a subtype of the Collection Interface, but it's still considered part of the Collections Framework. Maps in Java are objects that store associations between keys and values, or key/value pairs. Both keys and values are objects. The keys must be unique, but the values can be duplicated.
Here is how to declare a Map:
Map<KeyType, ValueType> mapName;
Basic methods of Java Map Interface
The Java Map Interface provides several useful methods. Here are some of them:
put(Key k, Value v)
: Inserts a key/value pair into the map. If the key already exists, its value is overwritten.get(Object key)
: Returns the value to which the specified key is mapped, or null if there is no mapping for the key.remove(Object key)
: Removes the key/value pair for this key.containsKey(Object key)
: Checks if the map contains a mapping for the specified key.size()
: Returns the number of key/value pairs in the map.isEmpty()
: Checks if the map contains no key/value pairs.clear()
: Removes all key/value pairs from the map.
Map Implementations
The Map Interface has several implementations in Java:
HashMap
: This class uses a hash table to implement the Map interface. It allows null values and keys. It doesn't maintain any order.LinkedHashMap
: This class extends HashMap but maintains insertion order.TreeMap
: This class implements a tree structure, and the objects are sorted in ascending order.Hashtable
: This is a synchronized implementation of Map. Unlike HashMap, it doesn't allow null keys or values.
Working with HashMap
Let's create a simple example using HashMap:
import java.util.*;
public class Example {
public static void main(String[] args)
{
Map<String, Integer> numbers = new HashMap<>();
// Insert elements
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
// Accessing elements
System.out.println(numbers.get("Two"));
// Removing elements
numbers.remove("Two");
// Printing all the keys
for (String i : numbers.keySet())
System.out.println(i);
}
}
In this example, we created a Map called numbers
that maps Strings to Integers. We added some key/value pairs, accessed a value, removed a key/value pair, and then printed all the keys.
Java Map Interface is a powerful tool for storing key/value pairs. It provides fast access and deletion of elements. It's important to choose the right implementation of Map based on your needs.