HashMap

 
/**
 * HashMap stores 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).
 * 
 * Performance:
 *      - put() and get() are O(1) average time
 *      - very fast for lookups by key
 */

package com.minte9.collections.maps;
import java.util.HashMap;
import java.util.Map;

public class HashMaps {
    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
    }
}

Loop

 
/**
 * How to iterate (loop) through a Map.
 * 
 * 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+) 
 * 
 * keySet()   -> iterate through keys only
 * values()   -> iterate through values only
 * entrySet() -> iterate through key/value pairs
 */

package com.minte9.collections.maps;

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

public class Loops {
    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
        }
    }
}






Questions and answers:
Clink on Option to Answer




1. What does a HashMap store?

  • a) Only values
  • b) Key-value pairs

2. What happens if you call put() with a key that already exists?

  • a) The old value is replaced
  • b) An error is thrown

3. What must HashMap keys correctly implement?

  • a) equals() and hashCode()
  • b) compareTo() and clone()

4. What is the average time complexity of get() and put()?

  • a) O(1)
  • b) O(n)

5. Which method is used to loop through keys only?

  • a) keySet()
  • b) entrySet()

6. Which method is used to loop through values only?

  • a) keySet()
  • b) values()

7. Which method lets you access BOTH the key and the value?

  • a) entrySet()
  • b) pairs()

8. What is Map.of() used for?

  • a) Quick initialization of a map (Java 9+)
  • b) Sorting a map


References: