12. List, Set & Map in Java
The three most-used interfaces of the Java Collections Framework: **List** (ordered, allows duplicates), **Set** (unique elements), **Map** (key-value pairs). This lecture covers the typical implementations: `ArrayList`, `HashSet`, `HashMap`.
What you'll learn
- 1Use `List` for ordered collections that allow duplicates
- 2Use `Set` for unique-element collections
- 3Use `Map` for key-value pairs
- 4Choose between `ArrayList`/`LinkedList`, `HashSet`/`TreeSet`, `HashMap`/`TreeMap`
Overview
The three most-used interfaces of the Java Collections Framework: **List** (ordered, allows duplicates), **Set** (unique elements), **Map** (key-value pairs). This lecture covers the typical implementations: `ArrayList`, `HashSet`, `HashMap`.
Core Concepts
1) `List`
import java.util.ArrayList;
import java.util.List;
List<String> names = new ArrayList<>();
names.add("Jisoo");
names.add("Minsu");
names.add("Jisoo"); // duplicates OK
System.out.println(names.size()); // 3
System.out.println(names.get(0)); // JisooUse `ArrayList` for fast random access. `LinkedList` is rarely the right choice in modern Java.
2) `Set`
import java.util.HashSet;
import java.util.Set;
Set<String> tags = new HashSet<>();
tags.add("java");
tags.add("spring");
tags.add("java"); // duplicate ignored
System.out.println(tags.size()); // 2Iteration order is not guaranteed in `HashSet`. Use `LinkedHashSet` for insertion order, `TreeSet` for sorted order.
3) `Map`
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> ages = new HashMap<>();
ages.put("Jisoo", 21);
ages.put("Minsu", 25);
System.out.println(ages.get("Jisoo")); // 21
System.out.println(ages.containsKey("X")); // false4) Iteration
for (var e : ages.entrySet()) {
System.out.println(e.getKey() + "=" + e.getValue());
}5) Immutable factories (JDK 9+)
List<Integer> nums = List.of(1, 2, 3); // immutable
Set<String> s = Set.of("a", "b");
Map<String, Integer> m = Map.of("x", 1, "y", 2);Examples
Example 1 β `ListDemo.java`
import java.util.ArrayList;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Jisoo");
names.add("Minsu");
names.add("Jisoo");
System.out.println(names);
System.out.println("size=" + names.size());
names.remove("Jisoo"); // removes the first match
System.out.println(names);
}
}**Output**
[Jisoo, Minsu, Jisoo]
size=3
[Minsu, Jisoo]Example 2 β `SetDemo.java`
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class SetDemo {
public static void main(String[] args) {
Set<String> hash = new HashSet<>();
hash.add("banana"); hash.add("apple"); hash.add("apple");
System.out.println("HashSet: " + hash);
Set<String> tree = new TreeSet<>(hash);
System.out.println("TreeSet (sorted): " + tree);
}
}**Output**
HashSet: [banana, apple]
TreeSet (sorted): [apple, banana]**Note:** `HashSet` order is implementation-defined; `TreeSet` sorts naturally.
Example 3 β `MapDemo.java`
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Jisoo", 21);
ages.put("Minsu", 25);
ages.put("Hana", 19);
for (var e : ages.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
ages.putIfAbsent("Jisoo", 99);
System.out.println("Jisoo=" + ages.get("Jisoo"));
}
}**Output**
Jisoo -> 21
Minsu -> 25
Hana -> 19
Jisoo=21**Note:** `putIfAbsent` only inserts if the key is missing.
Example 4 β `ImmutableFactory.java`
import java.util.List;
import java.util.Map;
public class ImmutableFactory {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3);
Map<String, Integer> map = Map.of("a", 1, "b", 2);
System.out.println(nums);
System.out.println(map);
try {
nums.add(4);
} catch (UnsupportedOperationException e) {
System.out.println("nums is immutable");
}
}
}**Output**
[1, 2, 3]
{a=1, b=2}
nums is immutableCommon Mistakes
- Trying to mutate a `List.of(...)` result β `UnsupportedOperationException`
- Using a mutable object as a `HashMap` key without proper `equals` / `hashCode`
- Iterating and calling `list.remove(o)` β `ConcurrentModificationException` (use `Iterator.remove()`)
- Boxing primitives in tight loops with `List<Integer>` (consider `int[]` or `IntStream`)
- Confusing `ArrayList` (random access) with `LinkedList` (insert/remove at ends)
Summary
- `List` = ordered, duplicates allowed
- `Set` = no duplicates
- `Map` = key β value
- Prefer `List.of` / `Set.of` / `Map.of` for read-only fixed data
Practice
# Practice - 12. List, Set, Map
## Exercise 1 β Word frequency
- File: `Homework01.java`
- Key concepts: `Map`, `getOrDefault`
Requirements
- Count the words in `"the quick brown fox jumps over the lazy dog the"`.
- Print each word and its count.
Expected output
the=3
quick=1
brown=1
fox=1
jumps=1
over=1
lazy=1
dog=1## Exercise 2 β Unique tags
- File: `Homework02.java`
- Key concepts: `Set`
Requirements
- Given `["java", "spring", "java", "boot", "spring"]`, print the unique tags in sorted order.
Expected output
[boot, java, spring]## Solutions After trying it yourself, compare with [`answer/`](./answer/).
Solution code (homework/answer/)
answer/Homework01.java
import java.util.LinkedHashMap;
import java.util.Map;
/** Word frequency. */
public class Homework01 {
public static void main(String[] args) {
String text = "the quick brown fox jumps over the lazy dog the";
Map<String, Integer> count = new LinkedHashMap<>();
for (String w : text.split(" ")) {
count.merge(w, 1, Integer::sum);
}
count.forEach((k, v) -> System.out.println(k + "=" + v));
}
}
answer/Homework02.java
import java.util.List;
import java.util.TreeSet;
/** Unique tags, sorted. */
public class Homework02 {
public static void main(String[] args) {
var tags = List.of("java", "spring", "java", "boot", "spring");
var unique = new TreeSet<>(tags);
System.out.println(unique);
}
}
Try It Yourself
cd 03_collections/12_list_set_map/src
javac ListDemo.java
java ListDemoNext Lecture
[13_Generics](../13_μ λ€λ¦/) β type parameters and wildcards.
All lecture materials and example code are openly available on GitHub.
View on GitHub β