JVM / Java / Collections / Maps

1. Key-value pairs

The keys must be unique, values may be duplicates. If we put() a value using a key that alreasy exists, the old value is overwritten. Internaly HashMap uses hashing to store the items in buckets. - hashCode(key) to finds the bucket - equals(key) to resolve collisions (same bucket) Keys must implement proper equals() and hashCode(), String already does. Time Complexity: - put() and get() are O(1) average time - very fast for lookups by key
 
package collections.maps;

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

public class HashMapExample {
    public static void main(String[] args) {
    
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Mary", 10);
        scores.put("Mary", 20); // overrites value for key "Mary"
        scores.put("John", 20);
        scores.put("Boby", 16);

        System.out.println(scores); // {John=20, Boby=16, Mary=20}
        System.out.println(scores.get("John"));  // 20
    }
}

2. Map Iteration

We can iterate through keys, values pairs. - keySet() -> iterate through keys only - values() -> iterate through values only - entrySet() -> iterate through key/value pairs
 
/**
 * Java does not support Javascript style object literals.
 *      let map = { a:1, b:2 }  // ❌ NOT valid in Java
 * 
 * But Java has alternatives to initialize a map without put().
 *      Map.of() (Java 9+) 
 */
import java.util.HashMap;
import java.util.Map;

public class MapLoop {
    public static void main(String[] args) {
    
        Map<String, Integer> scores = Map.of(  // Java 9+
            "Mary", 10,
            "John", 20,
            "Boby", 16
        );

        // Using put() (most common)
        scores = new HashMap<>();
        scores.put("Mary", 10);
        scores.put("John", 20);
        scores.put("Boby", 16);

        // Loop 1: keys only
        for (String key : scores.keySet()) {
            System.out.println(key);  // John Mary Boby
        }

        // Loop 2: values only
        for (Integer value : scores.values()){
            System.out.println(value);  // 20 16 10
        }

        // Loop 3: both keys and values
        for(Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
                // John 20
                // Boby 16
                // Mary 10
        }
    }
}




References: