Java Map Interface
Key-value pair storage for efficient data mapping
πΊοΈ What is Map?
Map is a Java interface that stores data in key-value pairs. Each key is unique and maps to exactly one value, making it perfect for lookups and associations.
// Simple Map example
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
System.out.println(ages.get("Alice")); // 25
Map Key Features
Key-Value Pairs
Store data as key-value associations
Map<String, String> capitals = new HashMap<>();
capitals.put("USA", "Washington");
capitals.put("France", "Paris");
capitals.put("Japan", "Tokyo");
Unique Keys
Each key can appear only once
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 85);
scores.put("Alice", 90); // Overwrites previous
// Alice now has score 90
Fast Lookup
Quick access to values by key
Map<String, String> phonebook = new HashMap<>();
phonebook.put("John", "123-456-7890");
String phone = phonebook.get("John");
// Instant lookup by key
Multiple Types
HashMap, TreeMap, LinkedHashMap
Map<String, Integer> hashMap = new HashMap<>();
Map<String, Integer> treeMap = new TreeMap<>();
Map<String, Integer> linkedMap = new LinkedHashMap<>();
πΉ Basic Map Operations
Essential operations for working with Maps:
import java.util.*;
public class MapExample {
public static void main(String[] args) {
// Create a Map
Map<String, Integer> studentGrades = new HashMap<>();
// Add key-value pairs
studentGrades.put("Alice", 85);
studentGrades.put("Bob", 92);
studentGrades.put("Charlie", 78);
// Get value by key
int aliceGrade = studentGrades.get("Alice");
System.out.println("Alice's grade: " + aliceGrade);
// Check if key exists
if (studentGrades.containsKey("Bob")) {
System.out.println("Bob is in the class");
}
// Update value
studentGrades.put("Alice", 88); // Updates Alice's grade
// Remove entry
studentGrades.remove("Charlie");
// Display all entries
System.out.println("Final grades: " + studentGrades);
}
}
Output:
Alice's grade: 85
Bob is in the class
Final grades: {Alice=88, Bob=92}
πΉ Iterating Through Maps
Different ways to loop through Map entries:
Map<String, Integer> inventory = new HashMap<>();
inventory.put("Apples", 50);
inventory.put("Bananas", 30);
inventory.put("Oranges", 25);
// Method 1: Using entrySet()
System.out.println("Method 1 - Entry Set:");
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Method 2: Using keySet()
System.out.println("\nMethod 2 - Key Set:");
for (String fruit : inventory.keySet()) {
System.out.println(fruit + ": " + inventory.get(fruit));
}
// Method 3: Using values()
System.out.println("\nMethod 3 - Values only:");
for (Integer quantity : inventory.values()) {
System.out.println("Quantity: " + quantity);
}
// Method 4: Using forEach (Java 8+)
System.out.println("\nMethod 4 - forEach:");
inventory.forEach((fruit, quantity) ->
System.out.println(fruit + " -> " + quantity));
Output:
Method 1 - Entry Set:
Apples: 50
Bananas: 30
Oranges: 25
Method 2 - Key Set:
Apples: 50
Bananas: 30
Oranges: 25
πΉ Common Map Methods
Essential methods for Map manipulation:
Map<String, String> countries = new HashMap<>();
countries.put("US", "United States");
countries.put("UK", "United Kingdom");
countries.put("FR", "France");
// Size and emptiness
System.out.println("Size: " + countries.size()); // 3
System.out.println("Is empty: " + countries.isEmpty()); // false
// Checking existence
System.out.println("Contains key 'US': " + countries.containsKey("US")); // true
System.out.println("Contains value 'France': " + countries.containsValue("France")); // true
// Safe retrieval with default
String germany = countries.getOrDefault("DE", "Not found");
System.out.println("Germany: " + germany); // Not found
// Replace operations
countries.replace("UK", "Great Britain");
countries.replaceAll((key, value) -> value.toUpperCase());
// Merge operation
countries.merge("DE", "Germany", (oldVal, newVal) -> newVal);
System.out.println("Final map: " + countries);
Output:
Size: 3
Is empty: false
Contains key 'US': true
Contains value 'France': true
Germany: Not found
Final map: {US=UNITED STATES, UK=GREAT BRITAIN, FR=FRANCE, DE=Germany}