Table of Contents
In this tutorial, you’ll learn about Maps in Java, HashMap, Key Characteristics of HashMap, Declaration and Initialization, TreeMap, Key Characteristics of TreeMap, Common Operations for HashMap and TreeMap , Key Differences and more along with examples.
What is Maps in Java
- Map is an interface that belongs to the Java Collections Framework.
- It represents a collection of key-value pairs, where each key is associated with a corresponding value.
- Maps allow for efficient retrieval and manipulation of data based on unique keys.
- In Java, HashMap and TreeMap are two essential implementations of the Map interface, each serving distinct purposes within the Java Collections Framework.
HashMap
- A HashMap is a part of Java’s Collection Framework that implements the Map interface.
- It is used to store key-value pairs, where each key is unique.
- HashMap uses a hash table for storing the map.
- This allows for fast retrieval of values based on their associated keys.
- It is important to note that HashMap does not maintain any order for its elements.
Key Characteristics of HashMap
- Key-Value Storage: Each entry in a HashMap consists of a key and a value. The keys are unique, while the values can be duplicated.
- Hash Table: Uses a hash table to store the map, which allows for constant-time performance (O(1)) for basic operations such as adding, removing, and retrieving elements.
- Null Values and Keys: Allows one null key and multiple null values.
- Non-Ordered: Does not maintain any order of the elements.
Declaration and Initialization
Declaration
To use HashMap, you need to import it from the java.util package and then declare it.
import java.util.HashMap;
HashMap<String, Integer> scores;
Initialization
You can initialize the HashMap using the new keyword.
scores = new HashMap<>();
Combined Declaration and Initialization
You can combine both declaration and initialization in a single line.
HashMap<String, Integer> scores = new HashMap<>();
Adding and Retrieving Elements
Adding Elements
Use the put method to add key-value pairs to the HashMap.
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 95);
Retrieving Elements
Use the get method to retrieve the value associated with a specific key.
int bobScore = scores.get("Bob");
System.out.println("Bob's Score: " + bobScore); // Outputs: Bob's Score: 85
TreeMap
- A TreeMap is a part of Java’s Collection Framework that implements the NavigableMap interface, which is a subtype of the SortedMap interface.
- Unlike HashMap, TreeMap stores key-value pairs in a sorted order, based on the natural ordering of its keys or a custom comparator provided at the time of creation.
- It uses a Red-Black tree as its underlying data structure, ensuring that the map is always in sorted order.
Key Characteristics of TreeMap
- Key-Value Storage: Each entry in a TreeMap consists of a key and a value. The keys must be unique.
- Sorted Order: Maintains the keys in a sorted order, either based on their natural order or a custom comparator.
- Red-Black Tree: Uses a Red-Black tree, which is a self-balancing binary search tree.
- No Null Keys: Does not allow null keys, but null values are permitted.
- Logarithmic Time Performance: Provides O(log n) time complexity for basic operations like add, remove, and get.
Declaration and Initialization
Declaration
To use TreeMap, you need to import it from the java.util package and then declare it.
import java.util.TreeMap;
TreeMap<String, Integer> scores;
Initialization
You can initialize the TreeMap using the new keyword.
scores = new TreeMap<>();
Combined Declaration and Initialization
You can combine both declaration and initialization in a single line.
TreeMap<String, Integer> scores = new TreeMap<>();
Adding and Retrieving Elements
Adding Elements
Use the put method to add key-value pairs to the TreeMap.
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 95);
Retrieving Elements
Use the get method to retrieve the value associated with a specific key.
int bobScore = scores.get("Bob");
System.out.println("Bob's Score: " + bobScore); // Outputs: Bob's Score: 85
Key Differences
Feature | HashMap | TreeMap |
---|---|---|
Ordering | Does not guarantee any specific order of the keys | Orders the keys based on their natural order or a provided comparator |
Performance | Offers constant-time performance for basic operations (add, remove, and get), assuming a good hash function | Provides O(log n) time complexity for basic operations due to the underlying red-black tree structure |
Sorting | Does not sort keys; order is not guaranteed | Maintains keys in sorted order |
Common Operations for HashMap and TreeMap
Iterating Through Entries:
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
Checking if a Key Exists:
boolean isBobPresent = scores.containsKey("Bob");
Checking if a Value Exists:
boolean isScorePresent = scores.containsValue(85);
Removing Elements:
scores.remove("Bob");
Example: Using HashMap
Let’s consider a scenario where we want to map student names to their scores.
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
// Declaration and Initialization
HashMap<String, Integer> studentScores = new HashMap<>();
// Adding elements to the HashMap
studentScores.put("Alice", 90);
studentScores.put("Bob", 85);
studentScores.put("Charlie", 95);
// Displaying the HashMap
System.out.println("Student Scores: " + studentScores);
// Retrieving a score for a specific student
int bobScore = studentScores.get("Bob");
System.out.println("Bob's Score: " + bobScore);
// Checking if a particular student is in the HashMap
if (studentScores.containsKey("Alice")) {
System.out.println("Alice is in the HashMap");
} else {
System.out.println("Alice is not in the HashMap");
}
// Removing an element from the HashMap
studentScores.remove("Charlie");
System.out.println("Student Scores after removing Charlie: " + studentScores);
// Iterating through the HashMap
System.out.println("Iterating through the HashMap:");
for (HashMap.Entry<String, Integer> entry : studentScores.entrySet()) {
System.out.println("Student: " + entry.getKey() + ", Score: " + entry.getValue());
}
}
}
Output
Student Scores: {Bob=85, Alice=90, Charlie=95}
Bob's Score: 85
Alice is in the HashMap
Student Scores after removing Charlie: {Bob=85, Alice=90}
Iterating through the HashMap:
Student: Bob, Score: 85
Student: Alice, Score: 90
Example: Using TreeMap
Let’s consider a scenario where we want to map student names to their scores, and we want the student names to be sorted in natural (alphabetical) order.
import java.util.TreeMap;
import java.util.Map; // Import Map interface
import java.util.Map.Entry; // Import Map.Entry interface
public class TreeMapExample {
public static void main(String[] args) {
// Declaration and Initialization
TreeMap<String, Integer> studentScores = new TreeMap<>();
// Adding elements to the TreeMap
studentScores.put("Alice", 90);
studentScores.put("Bob", 85);
studentScores.put("Charlie", 95);
// Displaying the TreeMap
System.out.println("Student Scores: " + studentScores);
// Retrieving a score for a specific student
int bobScore = studentScores.get("Bob");
System.out.println("Bob's Score: " + bobScore);
// Checking if a particular student is in the TreeMap
if (studentScores.containsKey("Alice")) {
System.out.println("Alice is in the TreeMap");
} else {
System.out.println("Alice is not in the TreeMap");
}
// Removing an element from the TreeMap
studentScores.remove("Charlie");
System.out.println("Student Scores after removing Charlie: " + studentScores);
// Iterating through the TreeMap
System.out.println("Iterating through the TreeMap:");
for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
System.out.println("Student: " + entry.getKey() + ", Score: " + entry.getValue());
}
}
}
Output
Student Scores: {Alice=90, Bob=85, Charlie=95}
Bob's Score: 85
Alice is in the TreeMap
Student Scores after removing Charlie: {Alice=90, Bob=85}
Iterating through the TreeMap:
Student: Alice, Score: 90
Student: Bob, Score: 85