In Java, a HashMap is a part of the java.util package and implements the Map interface. It stores data in key-value pairs, where each key is unique and maps to exactly one value.

🧠 Key Features of HashMap:

  • Fast access: Uses a technique called hashing to retrieve values quickly based on their keys.
  • No duplicate keys: If you try to insert a key that already exists, the new value will overwrite the old one.
  • Allows one null key and multiple null values.
  • Not ordered: The order of elements is not guaranteed (use LinkedHashMap if you need insertion order).
  • Not thread-safe: For concurrent access, use ConcurrentHashMap.

🧪 Example:

import java.util.HashMap;

public class Example {
public static void main(String[] args) {
HashMap scores = new HashMap<>();
scores.put(“Alice”, 90);
scores.put(“Bob”, 85);
scores.put(“Charlie”, 92);

    System.out.println(scores.get("Alice")); // Output: 90
}

}Java’s HashMap class offers a rich set of methods to manage key-value pairs efficiently. Here’s a handy breakdown of the most commonly used ones:

🔑 Basic Operations

  • put(K key, V value) – Adds or updates a key-value pair.
  • get(Object key) – Retrieves the value for a given key.
  • remove(Object key) – Deletes the entry for the specified key.
  • clear() – Removes all entries from the map.
  • size() – Returns the number of key-value pairs.
  • isEmpty() – Checks if the map is empty.

🔍 Search & Check

  • containsKey(Object key) – Checks if a key exists.
  • containsValue(Object value) – Checks if a value exists.
  • getOrDefault(Object key, V defaultValue) – Returns the value or a default if the key isn’t found.

🛠️ Advanced Utilities

  • putIfAbsent(K key, V value) – Adds a key-value pair only if the key isn’t already present.
  • replace(K key, V value) – Replaces the value for a key if it exists.
  • replace(K key, V oldValue, V newValue) – Replaces only if the current value matches the old one.
  • merge(K key, V value, BiFunction) – Combines values for duplicate keys using a function.
  • compute(K key, BiFunction) – Recomputes the value for a key.
  • computeIfAbsent(K key, Function) – Computes and adds a value if the key is missing.
  • computeIfPresent(K key, BiFunction) – Updates the value only if the key exists.

🔄 Iteration & Views

  • keySet() – Returns a Set of all keys.
  • values() – Returns a Collection of all values.
  • entrySet() – Returns a Set of all key-value pairs.
  • forEach(BiConsumer) – Performs an action for each entry.

Leave a Reply

Your email address will not be published. Required fields are marked *