AnyCompiler

The Collections Framework

HashMap<K, V> stores key-value pairs. put(key, value) inserts or updates an entry, and get(key) retrieves it — a HashMap gives no guarantee about iteration order, so code that depends on a particular order needs a different structure.

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> ages = new HashMap<>();
        ages.put("Alice", 30);
        ages.put("Bob", 25);
        System.out.println(ages.get("Alice"));
        System.out.println(ages.get("Bob"));
    }
}
Output
30
25

HashSet

HashSet stores unique values with no duplicates — adding a value that's already present is simply a no-op, which is why numbers.size() below is 3, not 4, even though add() was called four times.

import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        HashSet<Integer> numbers = new HashSet<>();
        numbers.add(5);
        numbers.add(3);
        numbers.add(5);
        numbers.add(1);
        System.out.println(numbers.size());
        System.out.println(numbers.contains(3));
    }
}
Output
3
true

Next: lambdas and streams — Java's modern, functional-flavored way to write inline behavior and transform collections.

Practice exercise

Create a HashMap<String, Integer> named ages. Put "Alice" -> 30 and "Bob" -> 25. Print ages.get("Alice").