SyntaxStudy
Sign Up
Java Beginner 1 min read

HashMap and HashSet

HashMap is the most widely used Map implementation in Java. It stores key-value pairs in a hash table, giving O(1) average-time complexity for get, put, and containsKey operations. Keys must be unique; if you put a value with an existing key, the old value is replaced. HashMap permits one null key and multiple null values, and its iteration order is not guaranteed. HashSet is built on top of HashMap internally and stores only unique elements. It provides O(1) average-time complexity for add, remove, and contains. Like HashMap, it does not maintain insertion order. When you need a set of unique items and fast membership checks, HashSet is your first choice. When working with these collections, it is important to understand the contract between hashCode() and equals(). Two objects that are equal according to equals() must return the same hashCode(). If you use custom objects as HashMap keys or HashSet elements, you must override both methods to ensure correct behaviour and avoid hard-to-find bugs.
Example
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class MapSetDemo {
    public static void main(String[] args) {
        // --- HashMap ---
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Alice", 95);
        scores.put("Bob",   87);
        scores.put("Carol", 92);
        scores.put("Alice", 98); // overwrites previous value

        System.out.println("Scores: " + scores);
        System.out.println("Alice's score: " + scores.get("Alice"));
        System.out.println("Contains Bob: " + scores.containsKey("Bob"));

        // Iterating entries
        System.out.println("\nAll entries:");
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.printf("  %-6s -> %d%n", entry.getKey(), entry.getValue());
        }

        // getOrDefault
        int dave = scores.getOrDefault("Dave", 0);
        System.out.println("Dave's score (default 0): " + dave);

        // --- HashSet ---
        Set<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Apple"); // duplicate, ignored
        fruits.add("Cherry");

        System.out.println("\nFruits set: " + fruits);
        System.out.println("Contains Banana: " + fruits.contains("Banana"));
        fruits.remove("Banana");
        System.out.println("After remove:    " + fruits);
    }
}