For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
In many real-world Java applications, we often need to associate one value with another—like a student's roll number with their name, or a country's code with its capital. The Map interface in Java is designed precisely for such use cases, allowing developers to store data in the form of key-value pairs.
Unlike Lists or Sets, a Map doesn't allow duplicate keys and provides efficient methods to insert, update, retrieve, or delete values based on keys. It's a core part of the Java Collections Framework and is widely used in everything from caching mechanisms to database lookups.
As you explore Java in greater depth, understanding the Map interface becomes essential for writing clean and efficient code. Structured learning, such as software engineering courses, can help reinforce these core concepts with practical examples.
The map interface in Java (java.util.Map) is a core part of the Java Collections Framework that represents a collection of key-value pairs. Unlike Lists or Sets that store individual elements, maps store entries, each containing a key and its associated value.
The defining characteristics of the Map interface in Java include:
Here's a simple representation of how a map stores data:
Key | Value |
"name" | "Mary Vue" |
1 | "First Place" |
42.5 | 100 |
The map interface in Java collections sits at the top of a hierarchy of map implementations:
Must read: What is Java Interface?
The map interface in Java establishes a contract that all implementing classes must follow. Understanding this contract is essential for effectively using maps.
Also check: Java Classes and Objects
Here's the core declaration of the Map interface:
public interface Map<K, V> {
// Core methods
V put(K key, V value);
V get(Object key);
V remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
int size();
boolean isEmpty();
void clear();
// ... other methods
}
The methods of map interface in Java provide a comprehensive API for working with key-value pairs. Let's explore the most important methods:
Method | Description | Return Value |
put(K key, V value) | Associates key with value | Previous value or null |
get(Object key) | Returns value for key | Value or null if not found |
remove(Object key) | Removes key-value mapping | Previous value or null |
containsKey(Object key) | Checks if key exists | Boolean |
containsValue(Object value) | Checks if value exists | Boolean |
size() | Number of key-value mappings | Integer |
isEmpty() | Checks if map is empty | Boolean |
clear() | Removes all mappings | void |
Method | Description |
putAll(Map<? extends K, ? extends V> m) | Copies all mappings from another map |
putIfAbsent(K key, V value) | Put only if key doesn't exist or is mapped to null |
The methods in map interface in Java include ways to obtain views of the map:
Set<K> keySet(); // View of map's keys
Collection<V> values(); // View of map's values
Set<Map.Entry<K, V>> entrySet(); // View of key-value pairs
These collection views provide a way to iterate over a map's contents.
The Map.Entry interface represents a key-value pair and provides these methods:
K getKey(); // Returns the key
V getValue(); // Returns the value
V setValue(V value); // Replaces the value (optional operation)
Since Java 8, the map interface in Java has added several powerful default methods:
// Compute a new value if key exists
V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction);
// Compute a value if key doesn't exist
V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction);
// Compute a new value if key exists and currently mapped to a value
V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction);
// Merge value with existing value
V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction);
// Get value or default if key not present
V getOrDefault(Object key, V defaultValue);
// Remove if key mapped to specific value
boolean remove(Object key, Object value);
// Replace value for key
V replace(K key, V value);
// Replace if key mapped to specific value
boolean replace(K key, V oldValue, V newValue);
// Apply function to each entry
void forEach(BiConsumer<? super K, ? super V> action);
// Replace all values with results of function
void replaceAll(BiFunction<? super K, ? super V, ? extends V> function);
The Java Collections Framework provides several implementations of the map interface in Java, each with different characteristics:
HashMap is the most commonly used implementation, offering O(1) average time complexity for basic operations:
// Creating a HashMap
Map<String, Integer> userScores = new HashMap<>();
// Adding entries
userScores.put("Mesa", 85);
userScores.put("Alina", 92);
userScores.put("Uma", 78);
// Retrieving a value
int aliceScore = userScores.get("Alice"); // Returns 92
Characteristics:
LinkedHashMap extends HashMap and maintains insertion order:
// Creating a LinkedHashMap
Map<String, Integer> userScores = new LinkedHashMap<>();
// Adding entries
userScores.put("Mesa", 85);
userScores.put("Alina", 92);
userScores.put("Uma", 78);
// Iterating (will be in insertion order)
for (Map.Entry<String, Integer> entry : userScores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Output:
Mesa: 85
Alina: 92
Uma: 78
Characteristics:
TreeMap implements SortedMap and NavigableMap interfaces, providing sorted keys:
// Creating a TreeMap
TreeMap<String, Integer> userScores = new TreeMap<>();
// Adding entries
userScores.put("Mesa", 85);
userScores.put("Alina", 92);
userScores.put("Uma", 78);
// Iterating (will be in sorted key order)
for (Map.Entry<String, Integer> entry : userScores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Output:
Mesa: 92
Alina: 78
Uma: 85
Characteristics:
EnumMap is a specialized implementation for enum keys:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
// Creating an EnumMap
EnumMap<Day, String> schedule = new EnumMap<>(Day.class);
// Adding entries
schedule.put(Day.MONDAY, "Work");
schedule.put(Day.SATURDAY, "Weekend");
Characteristics:
Also read: Enum in Java
WeakHashMap uses weak references for keys, allowing entries to be garbage-collected:
Map<Object, String> weakMap = new WeakHashMap<>();
Characteristics:
ConcurrentHashMap provides thread-safe operations with high concurrency:
Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
Characteristics:
Let's explore some practical examples using the map interface in Java:
Problem Statement: Count the frequency of words in a text.
import java.util.*;
public class WordFrequencyCounter {
public static Map<String, Integer> countWordFrequency(String text) {
// Split the text into words
String[] words = text.toLowerCase().split("\\W+");
// Create a map to store word frequencies
Map<String, Integer> wordFrequency = new HashMap<>();
// Count occurrences of each word
for (String word : words) {
if (word.isEmpty()) continue;
// Update count using getOrDefault (Java 8+)
wordFrequency.put(word, wordFrequency.getOrDefault(word, 0) + 1);
}
return wordFrequency;
}
public static void main(String[] args) {
String text = "To be or not to be, that is the question. " +
"Whether 'tis nobler in the mind to suffer " +
"the slings and arrows of outrageous fortune.";
Map<String, Integer> frequencies = countWordFrequency(text);
// Print results
System.out.println("Word Frequencies:");
frequencies.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue()));
}
}
Output:
Word Frequencies:
to: 3
the: 2
be: 2
or: 1
not: 1
that: 1
is: 1
question: 1
whether: 1
tis: 1
nobler: 1
in: 1
mind: 1
suffer: 1
slings: 1
and: 1
arrows: 1
of: 1
outrageous: 1
fortune: 1
Explanation: This example demonstrates using a HashMap to count word frequencies. It showcases:
Problem Statement: Create a student record system using a custom class as the map key.
import java.util.*;
class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() { return id; }
public String getName() { return name; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return id == student.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Student{id=" + id + ", name='" + name + "'}";
}
}
public class StudentRecords {
public static void main(String[] args) {
// Create a map to store student grades
Map<Student, Double> studentGrades = new HashMap<>();
// Add some students and their grades
studentGrades.put(new Student(1001, "Alice"), 3.8);
studentGrades.put(new Student(1002, "Bob"), 3.2);
studentGrades.put(new Student(1003, "Charlie"), 3.9);
// Try to add a duplicate student (same ID)
studentGrades.put(new Student(1001, "Alice Smith"), 4.0);
// Print all student grades
System.out.println("Student Grades:");
for (Map.Entry<Student, Double> entry : studentGrades.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Find a specific student
Student searchStudent = new Student(1002, "");
if (studentGrades.containsKey(searchStudent)) {
System.out.println("\nFound student 1002's grade: " +
studentGrades.get(searchStudent));
}
}
}
Output:
Student Grades:
Student{id=1001, name='Alice Smith'}: 4.0
Student{id=1002, name='Bob'}: 3.2
Student{id=1003, name='Charlie'}: 3.9
Found student 1002's grade: 3.2
Explanation: This example demonstrates:
The Map interface in Java is a fundamental part of the Collections Framework, allowing developers to store and manage data in key-value pairs efficiently. This guide covered its core concepts, popular implementations like HashMap and TreeMap, and practical use cases. Knowing when and how to use different Map types helps you write optimized and maintainable code.
As Java continues to evolve, newer Map methods offer greater flexibility and performance. By mastering these features, you can solve complex problems more effectively. For those pursuing structured Java learning, understanding Maps is a valuable step toward writing robust and scalable applications.
Both implement the Map interface, but Hashtable is synchronized (thread-safe) while HashMap is not. HashMap allows one null key and multiple null values, while Hashtable doesn't allow any null keys or values. HashMap is generally preferred in non-concurrent applications due to better performance.
Use TreeMap when you need the entries sorted by key. TreeMap keeps its keys in sorted order, which is useful for range queries or when you need to process entries in a specific order. However, TreeMap operations have O(log n) time complexity compared to HashMap's O(1) average case.
While technically possible, it's a bad practice. If a key's hashCode changes after being placed in a map, you might not be able to retrieve the associated value. Always use immutable objects or immutable properties of objects for map keys.
Unlike Hashtable, which locks the entire map for each operation, ConcurrentHashMap divides the map into segments (in earlier versions) or uses a more fine-grained lock per node (in newer versions). This allows multiple threads to modify different parts of the map simultaneously, improving concurrency.
The load factor determines when a HashMap will increase its internal capacity, which happens when (size / capacity) exceeds the load factor. The default is 0.75, meaning the map resizes when it's 75% full. A higher load factor saves memory but increases lookup time, while a lower load factor decreases collision probability but uses more memory.
HashMap doesn't maintain any order, but you can sort its entries by values using a list:
Map<String, Integer> map = new HashMap<>();
// Add entries...
// Convert to list and sort
List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(map.entrySet());
sortedEntries.sort(Map.Entry.comparingByValue());
// Or with streams in Java 8+
sortedEntries = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toList());
In Java 8+, HashMap uses balanced trees (instead of linked lists) when a bucket exceeds a certain threshold (typically 8 elements). This improves worst-case performance from O(n) to O(log n) for buckets with many entries due to hash collisions.
Since Java 9, you can use factory methods:
// Immutable map with up to 10 entries
Map<String, Integer> immutableMap = Map.of(
"one", 1,
"two", 2,
"three", 3
);
// For more entries
Map<String, Integer> largeImmutableMap = Map.ofEntries(
Map.entry("one", 1),
Map.entry("two", 2),
// more entries...
);
// Or in earlier versions
Map<String, Integer> unmodifiableMap =
Collections.unmodifiableMap(new HashMap<>(originalMap));
EnumMap is specifically designed for enum keys and is more efficient in terms of time and space complexity. It's implemented as an array where the ordinal value of the enum serves as the index, providing faster operations than a general-purpose HashMap.
LinkedHashMap maintains insertion order (or access order if configured appropriately) using a doubly-linked list, while HashMap doesn't maintain any order. LinkedHashMap is slightly slower for insertion and deletion operations and uses more memory due to the additional links.
WeakHashMap is useful for implementing caches where you don't want the presence of an entry in the map to prevent the key from being garbage collected. When a key is no longer referenced elsewhere in your program, its entry in the WeakHashMap will automatically be removed during the next garbage collection cycle.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.