DEV Community

Sudhakar V
Sudhakar V

Posted on

Map Interface in Java

The Map interface in Java represents a collection that stores elements as key-value pairs. Unlike List and Set, Map doesn't extend the Collection interface but is part of the Java Collections Framework.

1. Key Implementations of Map

Class Description
HashMap Uses hash table (no order, allows one null key)
LinkedHashMap Maintains insertion order
TreeMap Sorted by keys (natural order or comparator)
Hashtable Legacy, thread-safe (no null keys/values)
ConcurrentHashMap Thread-safe, high-performance alternative

2. Map Interface Methods (Detailed)

📌 Basic Operations

Method Description Example
V put(K key, V value) Adds key-value pair (replaces if key exists) map.put("Java", 1);
V get(Object key) Returns value for key (null if absent) Integer val = map.get("Java");
V remove(Object key) Removes and returns value for key map.remove("Java");
boolean containsKey(Object key) Checks if key exists map.containsKey("Java");
boolean containsValue(Object value) Checks if value exists map.containsValue(1);
int size() Returns number of mappings map.size();
boolean isEmpty() Checks if map is empty map.isEmpty();
void clear() Removes all mappings map.clear();

📌 Bulk Operations

Method Description Example
void putAll(Map<? extends K,? extends V> m) Copies all from another map map.putAll(otherMap);
Set<K> keySet() Returns set of all keys Set<String> keys = map.keySet();
Collection<V> values() Returns collection of all values Collection<Integer> vals = map.values();
Set<Map.Entry<K,V>> entrySet() Returns set of key-value pairs Set<Entry<String,Integer>> entries = map.entrySet();

📌 Java 8+ Methods

Method Description Example
V getOrDefault(Object key, V defaultValue) Returns value or default map.getOrDefault("C++", 0);
V putIfAbsent(K key, V value) Puts only if key absent map.putIfAbsent("Java", 2);
boolean remove(Object key, Object value) Removes only if key-value matches map.remove("Java", 1);
V replace(K key, V value) Replaces value for key map.replace("Java", 2);
void replaceAll(BiFunction<K,V,V> function) Replaces all values map.replaceAll((k,v) -> v+1);
V compute(K key, BiFunction<K,V,V> remapping) Computes new value map.compute("Java", (k,v) -> v+1);
V merge(K key, V value, BiFunction<V,V,V> remapping) Merges values map.merge("Java", 1, Integer::sum);

3. Example: Using Map Methods

import java.util.*;

public class MapExample {
    public static void main(String[] args) {
        Map<String, Integer> languages = new HashMap<>();

        // 1. Adding elements
        languages.put("Java", 1);
        languages.put("Python", 2);
        languages.put("C++", 3);
        System.out.println(languages);  // {Java=1, C++=3, Python=2}

        // 2. Accessing elements
        int javaRank = languages.get("Java");
        System.out.println("Java's rank: " + javaRank);  // 1

        // 3. Checking existence
        System.out.println("Contains Java? " + languages.containsKey("Java"));  // true
        System.out.println("Contains rank 2? " + languages.containsValue(2));   // true

        // 4. Iterating
        System.out.println("\nAll languages:");
        for (Map.Entry<String, Integer> entry : languages.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        // 5. Java 8 methods
        languages.putIfAbsent("JavaScript", 4);
        languages.compute("Java", (k,v) -> v+10);
        System.out.println("\nAfter updates: " + languages);

        // 6. Removing
        languages.remove("C++");
        System.out.println("After removal: " + languages);
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Key Points to Remember

✔ Stores key-value pairs (keys must be unique)
✔ Three collection views: keySet(), values(), entrySet()
✔ HashMap is most common (no order, O(1) operations)
✔ TreeMap keeps keys sorted (O(log n) operations)
✔ Null handling:

  • HashMap: 1 null key, multiple null values
  • TreeMap: No null keys
  • Hashtable: No null keys/values

5. When to Use Which Map?

Requirement Best Choice
General purpose HashMap
Maintain insertion order LinkedHashMap
Sorted keys TreeMap
Thread-safe ConcurrentHashMap
Legacy thread-safe Hashtable

6. Performance Comparison

Operation HashMap TreeMap LinkedHashMap
put() O(1) O(log n) O(1)
get() O(1) O(log n) O(1)
containsKey() O(1) O(log n) O(1)
next() O(h/n) O(log n) O(1)

This comprehensive guide covers all major aspects of Java's Map interface. Let me know if you need any clarification or additional details!

Top comments (0)