Map and HashMap

Map is a key-value pair collection. This lesson covers Map usage.

Map Interface Characteristics

Feature Description
Key-value pairs Each element contains a key and value
Unique keys Keys are unique, values can repeat
Unordered HashMap is unordered

HashMap

HashMap is the most commonly used Map implementation.

Creating HashMap

JAVA
import java.util.HashMap;
import java.util.Map;

Map<String, Integer> map1 = new HashMap<>();
Map<String, Integer> map2 = new HashMap<>(100);  // Specified capacity
Map<String, Integer> map3 = new HashMap<>(map1);  // From another Map

Basic Operations

JAVA
import java.util.HashMap;
import java.util.Map;

public class HashMapDemo {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        
        // Add key-value pairs
        scores.put("Alice", 95);
        scores.put("Bob", 88);
        scores.put("Charlie", 92);
        System.out.println("Map: " + scores);
        
        // Get value
        int aliceScore = scores.get("Alice");
        System.out.println("Alice's score: " + aliceScore);
        
        // Get value (return default if key doesn't exist)
        int davidScore = scores.getOrDefault("David", 0);
        System.out.println("David's score: " + davidScore);
        
        // Check
        System.out.println("Contains Alice: " + scores.containsKey("Alice"));
        System.out.println("Contains 95: " + scores.containsValue(95));
        System.out.println("Size: " + scores.size());
        
        // Modify
        scores.put("Alice", 98);  // Overwrite old value
        System.out.println("Updated Alice: " + scores.get("Alice"));
        
        // Delete
        scores.remove("Bob");
        System.out.println("After remove: " + scores);
    }
}

putIfAbsent

JAVA
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 95);

// Only add if key doesn't exist
map.putIfAbsent("Alice", 100);  // Won't overwrite
map.putIfAbsent("Bob", 88);     // Will add

System.out.println(map);  // {Alice=95, Bob=88}

Traversal Methods

Method 1: Traverse keySet

JAVA
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 95);
map.put("Bob", 88);
map.put("Charlie", 92);

for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
}

Method 2: Traverse values

JAVA
for (int value : map.values()) {
    System.out.println(value);
}

Method 3: Traverse entrySet

JAVA
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

Method 4: Lambda

JAVA
map.forEach((key, value) -> System.out.println(key + ": " + value));

Example: Map Traversal

JAVA
import java.util.HashMap;
import java.util.Map;

public class MapTraversal {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Alice", 95);
        scores.put("Bob", 88);
        scores.put("Charlie", 92);
        
        // Traverse entrySet
        System.out.println("=== entrySet traversal ===");
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
        
        // Lambda traversal
        System.out.println("=== Lambda traversal ===");
        scores.forEach((name, score) -> 
            System.out.println(name + "'s score is " + score));
    }
}
▶ Try it Yourself

TreeMap

TreeMap is based on red-black tree and keys are automatically sorted.

Example: TreeMap

JAVA
import java.util.Map;
import java.util.TreeMap;

public class TreeMapDemo {
    public static void main(String[] args) {
        Map<String, Integer> map = new TreeMap<>();
        map.put("Charlie", 92);
        map.put("Alice", 95);
        map.put("Bob", 88);
        
        // Sorted by key
        map.forEach((key, value) -> 
            System.out.println(key + ": " + value));
        // Alice: 95
        // Bob: 88
        // Charlie: 92
    }
}
▶ Try it Yourself

LinkedHashMap

LinkedHashMap maintains insertion order.

Example: LinkedHashMap

JAVA
import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapDemo {
    public static void main(String[] args) {
        Map<String, Integer> map = new LinkedHashMap<>();
        map.put("Charlie", 92);
        map.put("Alice", 95);
        map.put("Bob", 88);
        
        // Insertion order
        map.forEach((key, value) -> 
            System.out.println(key + ": " + value));
        // Charlie: 92
        // Alice: 95
        // Bob: 88
    }
}
▶ Try it Yourself

Common Map Methods

Method Description
put(K, V) Add key-value pair
get(K) Get value
getOrDefault(K, V) Get value, return default if not exists
putIfAbsent(K, V) Add if key doesn't exist
remove(K) Remove key-value pair
containsKey(K) Contains key
containsValue(V) Contains value
keySet() All keys as Set
values() All values as Collection
entrySet() All entries as Set
size() Size
isEmpty() Is empty
clear() Clear all
putAll(Map) Add all

Map Comparison

Feature HashMap TreeMap LinkedHashMap
Order Unordered Sorted Insertion order
Implementation Hash table Red-black tree Linked list + hash table
Performance O(1) O(log n) O(1)
null key 1 allowed Not allowed 1 allowed

Example: Word Frequency Counter

JAVA
import java.util.HashMap;
import java.util.Map;

public class WordCount {
    public static Map<String, Integer> count(String text) {
        Map<String, Integer> map = new HashMap<>();
        String[] words = text.toLowerCase().split("\\s+");
        
        for (String word : words) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }
        
        return map;
    }
    
    public static void main(String[] args) {
        String text = "hello world hello java world hello";
        Map<String, Integer> counts = count(text);
        
        counts.forEach((word, count) -> 
            System.out.println(word + ": " + count));
        // hello: 3
        // world: 2
        // java: 1
    }
}

Example: Grouping

JAVA
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GroupBy {
    public static Map<String, List<String>> groupByFirstChar(List<String> list) {
        Map<String, List<String>> map = new HashMap<>();
        
        for (String s : list) {
            String key = s.substring(0, 1).toUpperCase();
            map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
        }
        
        return map;
    }
    
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        names.add("David");
        names.add("Eve");
        
        Map<String, List<String>> groups = groupByFirstChar(names);
        groups.forEach((key, value) -> 
            System.out.println(key + ": " + value));
        // A: [Alice]
        // B: [Bob]
        // C: [Charlie]
        // D: [David]
        // E: [Eve]
    }
}

❓ Frequently Asked Questions

Q Can HashMap keys be null?
A Yes, only one null key allowed. Values can have multiple nulls.
Q How does HashMap detect duplicate keys?
A First compares hashCode, then compares equals, similar to HashSet.
Q Is HashMap thread-safe?
A No. Use ConcurrentHashMap for multi-threaded scenarios.

📖 Summary

📝 Exercises

  1. Word frequency: Count occurrences of each word in a string
  2. Grouping: Group students by grade level (Excellent/Good/Pass/Fail)
  3. Cache: Implement a simple cache using HashMap

Next Lesson

In the next lesson, we'll learn about Generics — understanding Java generics.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏