2.4 Maps Explained
Maps in Java are a fundamental part of the Java Collections Framework, providing a way to store and manipulate key-value pairs. Understanding maps is crucial for managing data where each element is associated with a unique key.
Key Concepts
1. Map Interface
The Map
interface represents a collection of key-value pairs where each key is unique. It does not extend the Collection
interface but is a part of the Java Collections Framework. Common methods include put
, get
, remove
, and containsKey
.
Example
Mapmap = new HashMap<>(); map.put("Apple", 1); map.put("Banana", 2); map.put("Cherry", 3); System.out.println(map.get("Banana")); // Output: 2
2. HashMap
A HashMap
is a collection that uses a hash table for storage. It provides constant-time performance for basic operations like put, get, and remove. The order of elements is not guaranteed.
Example
MaphashMap = new HashMap<>(); hashMap.put("Dog", 1); hashMap.put("Cat", 2); hashMap.put("Bird", 3); System.out.println(hashMap); // Output: {Dog=1, Cat=2, Bird=3} (order may vary)
3. LinkedHashMap
A LinkedHashMap
maintains the insertion order of elements. It provides constant-time performance for basic operations and maintains a doubly-linked list running through all of its entries.
Example
MaplinkedHashMap = new LinkedHashMap<>(); linkedHashMap.put("Car", 1); linkedHashMap.put("Bike", 2); linkedHashMap.put("Truck", 3); System.out.println(linkedHashMap); // Output: {Car=1, Bike=2, Truck=3}
4. TreeMap
A TreeMap
stores elements in a sorted order based on the keys. It uses a red-black tree structure and provides logarithmic-time performance for basic operations. The elements are sorted according to their natural ordering or by a specified comparator.
Example
MaptreeMap = new TreeMap<>(); treeMap.put("Banana", 2); treeMap.put("Apple", 1); treeMap.put("Cherry", 3); System.out.println(treeMap); // Output: {Apple=1, Banana=2, Cherry=3}
Examples and Analogies
Think of a Map
as a dictionary where each word (key) has a definition (value). A HashMap
is like a dictionary where words are stored without any specific order, a LinkedHashMap
is like a dictionary where words are stored in the order they were added, and a TreeMap
is like a dictionary where words are stored in alphabetical order.
By mastering maps, you can efficiently manage and manipulate key-value pairs in your Java SE 11 applications.