Java ยท Chapter 35 of 42

Java Collections: Set and Map

Set is a collection that stores unique elements with no duplicates, commonly implemented as HashSet (unordered) or TreeSet (sorted). Map stores key-value pairs, commonly implemented as HashMap or TreeMap.

HashMap provides fast average O(1) lookups by key, while TreeMap keeps keys sorted at the cost of O(log n) operations.

Syntax
Set<Type> s = new HashSet<>();
Map<K,V> m = new HashMap<>();
m.put(key, value);

Using Set

HashSet automatically rejects duplicate values when you call add(). It does not guarantee any particular ordering of elements.

Using Map

Map.put(key, value) stores an entry, get(key) retrieves it, and containsKey() checks for existence. Keys must be unique; values can repeat.

Example 1 (java)
import java.util.HashSet;
import java.util.HashMap;
import java.util.Set;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    Set<String> names = new HashSet<>();
    names.add("Amy");
    names.add("Amy");
    System.out.println(names.size());

    Map<String, Integer> ages = new HashMap<>();
    ages.put("Amy", 25);
    System.out.println(ages.get("Amy"));
  }
}
Output
1
25

HashSet rejects the duplicate "Amy", and HashMap stores and retrieves a value by key.

Key points

  • Set stores only unique elements.
  • Map stores key-value pairs with unique keys.
  • HashMap and HashSet offer fast average-case operations.
  • TreeMap and TreeSet keep entries sorted.
๐Ÿ’ก Note: Choose HashMap/HashSet for speed, and TreeMap/TreeSet when sorted order matters.

๐Ÿ“ Quick Quiz

1. Can a Set contain duplicate elements?

2. What must be unique in a Map?

3. Which Map implementation keeps keys sorted?