In Java, a Map
is an object that maps keys to values. It is part of the Java Collections Framework and represents a collection of key-value pairs, where each key is associated with a single value. Unlike a Set
, which stores unique elements, a Map
allows duplicate values but requires unique keys.
A Map
is an interface that defines a collection of key-value pairs. The key acts as a unique identifier for each value in the map. If you try to insert a value with a key that already exists, the new value will replace the existing one.
LinkedHashMap
), while others do not (like HashMap
).To create a map, you first need to import the necessary classes from the java.util
package. You can instantiate a Map
using its concrete implementations.
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// Creating a HashMap
Map ageMap = new HashMap<>();
// Adding key-value pairs
ageMap.put("Alice", 30);
ageMap.put("Bob", 25);
ageMap.put("Charlie", 35);
ageMap.put("Diana", null); // Allowed null value
// Displaying the HashMap
System.out.println("Age Map: " + ageMap);
}
}
Output:
Age Map: {Alice=30, Bob=25, Charlie=35, Diana=null}
You can add key-value pairs to a map using the put()
method. If the key already exists, the existing value will be replaced.
Example: Adding Key-Value Pairs
ageMap.put("Eve", 28); // Adding a new entry
ageMap.put("Alice", 31); // Updating Alice's age
System.out.println("Updated Age Map: " + ageMap);
You can remove a key-value pair from a map using the remove()
method. If the key does not exist, the method does nothing.
Example: Removing Key-Value Pairs
ageMap.remove("Bob"); // Removing Bob's entry
System.out.println("After removing Bob: " + ageMap);
You can retrieve the value associated with a specific key using the get()
method. If the key does not exist, the method returns null
.
Example: Accessing Values
Integer aliceAge = ageMap.get("Alice");
System.out.println("Alice's age: " + aliceAge);
You can check if a map contains a specific key or value using the containsKey()
and containsValue()
methods.
Example: Checking for Keys and Values
boolean hasCharlie = ageMap.containsKey("Charlie");
boolean hasAge30 = ageMap.containsValue(30);
System.out.println("Contains Charlie? " + hasCharlie);
System.out.println("Contains age 30? " + hasAge30);
You can find out the number of key-value pairs in a map using the size()
method.
Example: Getting the Size
System.out.println("Size of the map: " + ageMap.size());
To remove all key-value pairs from a map, you can use the clear()
method.
Example: Clearing the Map
ageMap.clear();
System.out.println("After clearing the map: " + ageMap);
You can iterate over the entries of a map using different methods such as the enhanced for loop, entry set, or key set.
for (Map.Entry entry : ageMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
for (String key : ageMap.keySet()) {
System.out.println(key + ": " + ageMap.get(key));
}
Java 8 introduced the forEach
method for maps:
ageMap.forEach((key, value) -> {
System.out.println(key + ": " + value);
});
The average time complexity for basic operations in different map implementations is as follows:
HashMap:
TreeMap:
LinkedHashMap:
The memory usage of a Map
implementation can vary. For example, HashMap
typically uses more memory due to its array structure and linked lists for collision resolution. TreeMap
, while more memory-efficient for small datasets, requires additional space for maintaining the red-black tree structure.
Map
to store application settings as key-value pairs.You can merge two maps using the putAll()
method. If the same key exists in both maps, the value from the second map will overwrite the value from the first.
Example: Merging Two Maps
Map additionalAges = new HashMap<>();
additionalAges.put("Frank", 22);
additionalAges.put("Alice", 29); // Overwrites Alice's age
ageMap.putAll(additionalAges);
System.out.println("After merging: " + ageMap);
Java 8 introduced the Stream
API, which allows you to perform functional-style operations on collections, including maps.
Example: Mapping Values
ageMap = ageMap.entrySet()
.stream()
.filter(entry -> entry.getValue() != null) // Filter out null values
.collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue() + 1)); // Increment ages
System.out.println("Ages incremented by 1: " + ageMap);
While maps themselves do not provide a method for sorting, you can create a sorted representation of a map using TreeMap
or by sorting entries from a HashMap
.
Example: Sorting a HashMap
Map sortedMap = ageMap.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue()) // Sort by value
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
System.out.println("Sorted Map: " + sortedMap);
Let’s create a simple console application to manage product inventory using a Map
. This application will allow users to add products, view the inventory, and update product quantities.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class ProductInventory {
private Map inventory;
public ProductInventory() {
inventory = new HashMap<>();
}
public void addProduct(String name, int quantity) {
inventory.put(name, inventory.getOrDefault(name, 0) + quantity);
System.out.println("Added " + quantity + " units of " + name);
}
public void viewInventory() {
System.out.println("Product Inventory:");
inventory.forEach((name, quantity) -> {
System.out.println(name + ": " + quantity + " units");
});
}
public void updateProductQuantity(String name, int quantity) {
if (inventory.containsKey(name)) {
inventory.put(name, quantity);
System.out.println("Updated " + name + " to " + quantity + " units");
} else {
System.out.println("Product not found: " + name);
}
}
public static void main(String[] args) {
ProductInventory inventoryManager = new ProductInventory();
Scanner scanner = new Scanner(System.in);
String command;
System.out.println("Product Inventory Management System");
System.out.println("Commands: add [name] [quantity], view, update [name] [quantity], exit");
while (true) {
System.out.print("Enter command: ");
command = scanner.nextLine();
String[] parts = command.split(" ");
switch (parts[0]) {
case "add":
if (parts.length == 3) {
String name = parts[1];
int quantity = Integer.parseInt(parts[2]);
inventoryManager.addProduct(name, quantity);
} else {
System.out.println("Invalid command format. Use: add [name] [quantity]");
}
break;
case "view":
inventoryManager.viewInventory();
break;
case "update":
if (parts.length == 3) {
String name = parts[1];
int quantity = Integer.parseInt(parts[2]);
inventoryManager.updateProductQuantity(name, quantity);
} else {
System.out.println("Invalid command format. Use: update [name] [quantity]");
}
break;
case "exit":
System.out.println("Exiting Product Inventory Management System.");
scanner.close();
return;
default:
System.out.println("Unknown command.");
}
}
}
}
Map
of product names and their quantities, providing methods to add products, view the inventory, and update quantities.main
method provides a command-line interface for users to manage the product inventory.