Java HashMap

A HashMap in Java is part of the java.util package and is a data structure that stores key-value pairs. It implements the Map interface and allows you to store and retrieve data based on a key. HashMaps do not maintain any order of their elements.

1. Creating a HashMap

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
    }
}

2. Adding Entries

Use the put() method to add key-value pairs.

map.put("Apple", 3);
map.put("Banana", 5);
map.put("Cherry", 2);

3. Accessing Values

Use the get() method with a key to retrieve its corresponding value.

int quantity = map.get("Apple");
System.out.println("Quantity of Apples: " + quantity); // Outputs: Quantity of Apples: 3

4. Iterating Over a HashMap

You can iterate over the keys, values, or entries.

Iterating Over Keys:

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

Iterating Over Values:

for (Integer value : map.values()) {
    System.out.println("Value: " + value);
}

Iterating Over Entries:

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

5. Common Methods

  • containsKey(Object key) - Checks if the map contains the specified key.
  • containsValue(Object value) - Checks if the map contains the specified value.
  • remove(Object key) - Removes the key-value pair for the specified key.
  • size() - Returns the number of key-value pairs.
  • clear() - Removes all key-value pairs.

6. Key Takeaways

  • HashMap allows for fast retrieval of data using keys.
  • Does not maintain any order of elements.
  • Allows one null key and multiple null values.
  • Not synchronized; use Collections.synchronizedMap() or ConcurrentHashMap for thread safety.