View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Complete Guide to Map Interface in Java

Updated on 19/05/20255,037 Views

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.

Basics of Map Interface in Java

What is a Map in Java?

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:

  • Key Uniqueness: Each key can appear only once in a map
  • Value Association: Every key maps to exactly one value (which may be null for most implementations)
  • No Inherent Ordering: Unless using ordered implementations like TreeMap or LinkedHashMap
  • Not a Collection: Map interface does not extend the Collection interface, setting it apart from Lists, Sets, and Queues

Here's a simple representation of how a map stores data:

Key

Value

"name"

"Mary Vue"

1

"First Place"

42.5

100

Map Interface Hierarchy

The map interface in Java collections sits at the top of a hierarchy of map implementations:

Must read: What is Java Interface?

Java Map Interface Contract and Core Principles

The map interface in Java establishes a contract that all implementing classes must follow. Understanding this contract is essential for effectively using maps.

Contract Highlights

  1. Key Uniqueness: Maps cannot contain duplicate keys; each key maps to at most one value
  2. Equality-Based: Map operations rely on the equals() method for keys
  3. Hashability: Most implementations rely on the hashCode() method for efficient lookup
  4. Mutability: Maps can be mutable (modifiable) or immutable (read-only)
  5. Null Handling: Most implementations allow null keys and values (with TreeMap being a notable exception for keys)

Also check: Java Classes and Objects

Interface Declaration

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
}

Core Methods of the Map Interface in Java

The methods of map interface in Java provide a comprehensive API for working with key-value pairs. Let's explore the most important methods:

Basic Operations

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

Bulk Operations

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

Collection Views

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.

Entry Interface

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)

Java 8+ Enhancements

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);

Map Implementations in Java

The Java Collections Framework provides several implementations of the map interface in Java, each with different characteristics:

HashMap

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:

  • No guaranteed order of elements
  • Allows one null key and multiple null values
  • Not synchronized (not thread-safe)
  • Constant-time performance for basic operations (assuming good hash function)

LinkedHashMap

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:

  • Preserves insertion order
  • Slightly higher memory overhead than HashMap
  • Can be configured to maintain access order (LRU cache)
  • Otherwise has same properties as HashMap

TreeMap

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:

  • Keys are sorted in natural order or by a provided Comparator
  • O(log n) time complexity for most operations
  • Cannot contain null keys (but can have null values)
  • Implements NavigableMap with methods like lowerEntry(), floorEntry(), ceilingEntry(), and higherEntry()

EnumMap

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:

  • Very efficient for enum keys
  • Keys are stored in natural order (enum declaration order)
  • Cannot contain null keys

Also read: Enum in Java

WeakHashMap

WeakHashMap uses weak references for keys, allowing entries to be garbage-collected:

Map<Object, String> weakMap = new WeakHashMap<>();

Characteristics:

  • Entries are removed when keys are no longer referenced elsewhere
  • Useful for implementing caches
  • Behaves like HashMap otherwise

ConcurrentHashMap

ConcurrentHashMap provides thread-safe operations with high concurrency:

Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();

Characteristics:

  • Thread-safe without locking the entire table
  • Doesn't allow null keys or values
  • Offers higher concurrency than synchronized maps
  • Iterator is fail-safe (doesn't throw ConcurrentModificationException)

Practical Code Examples of Map Interface in Java

Let's explore some practical examples using the map interface in Java:

Example 1: Word Frequency Counter

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:

  • Basic map operations (put, getOrDefault)
  • Stream operations on map entries
  • Sorting map entries by value

Example 2: Custom Key Class with HashMap

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:

  • Using a custom class as a map key
  • Proper implementation of equals() and hashCode() for map keys
  • Key uniqueness (notice the update of Alice's grade)
  • Looking up values by key equality

Conclusion

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.

FAQs

1. How is HashMap different from Hashtable in Java?

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.

2. When should I use TreeMap instead of HashMap?

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.

3. Can I use a mutable object as a key in HashMap?

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.

4. How does ConcurrentHashMap achieve thread safety?

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.

5. What is the load factor in HashMap and why is it important?

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.

6. How can I sort a HashMap by values?

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());

7. What happens in a hash collision in HashMap?

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.

8. How can I create an immutable Map in Java?

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));

9. How is EnumMap different from HashMap with enum keys?

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.

10. What's the difference between HashMap and LinkedHashMap?

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.

11. When would you use WeakHashMap?

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.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.