Sets and Maps (course slides)
Java (java.util.Set, java.util.Map).
Sets
java
Set<String> uniqueNames = new HashSet<>();
uniqueNames.add("John");
uniqueNames.add("Joe");
uniqueNames.add("John"); // adding a duplicate does nothing
for (String name : uniqueNames) {
System.out.println(name);
}
uniqueNames.get(0); // does not compile - Sets have no defined order/index!
// Immutable set:
Set<Integer> primeNumbers = Set.of(2, 3, 5, 7);
primeNumbers.add(11); // crashes - the set is immutableSets vs Lists:
- Like Lists, can't hold primitive types directly, and can be mutable (
HashSet) or immutable (Set.of(...)). - Unlike Lists, no defined order (effectively random iteration order) — no indexing, no
.get(index). - Every element is unique — adding a duplicate is a silent no-op.
- For large collections, checking whether an element is contained is significantly faster than in a
List.
Maps
java
Map<String, Double> examScoresPerStudent = new HashMap<>(Map.of(
"John", 4.6,
"Lisa", 3.5,
"Jack", 2.7
));
double examScoreForJohn = examScoresPerStudent.get("John");
examScoresPerStudent.put("Sarah", 4.9);
examScoresPerStudent.put("Sarah", 4.3); // overwrites the existing value
for (String student : examScoresPerStudent.keySet()) {
double score = examScoresPerStudent.get(student);
System.out.println(student + " has the following exam score: " + score);
}
examScoresPerStudent.remove("John");
examScoresPerStudent.remove("John"); // removing again: no-op, nothing happensImmutable map:
java
Map<String, String> countriesAndCapitalCities = Map.of(
"Austria", "Vienna",
"Germany", "Berlin",
"Italy", "Rome"
);
countriesAndCapitalCities.put("Spain", "Madrid"); // crashes - immutableMaps:
- Store key/value pairs. Like Lists, can't hold primitives directly.
- Like Sets, no defined order.
- Keys are unique (like Set elements); values can repeat.
- Alternate names: Map = "Dictionary";
HashMap= a concrete "Hash Table" implementation. - Checking whether a key exists is very fast (same underlying mechanism as
Set).