# Collections — Core Java

Source: https://www.geekswithgeeks.com/en/core-java/java-collections

> Pick the right data structure from the List, Set and Map families, use generics for type safety, and reach for map helpers like merge and computeIfAbsent.

## The three families

**List** — ordered, duplicates allowed (`ArrayList`, `LinkedList`). **Set** — no duplicates (`HashSet`, `TreeSet`, `LinkedHashSet`). **Map** — key → value (`HashMap`, `TreeMap`, `LinkedHashMap`). Program to the interface, not the implementation.

## Everyday usage

Generics (`<String>`) give compile-time type safety. Iterate with for-each; use `getOrDefault`, `computeIfAbsent`, `merge` on maps to avoid null checks.

```java
Map<String, Integer> counts = new HashMap<>();
for (String w : words) {
    counts.merge(w, 1, Integer::sum);
}
List<String> names = new ArrayList<>(List.of("Ada", "Al"));
names.forEach(System.out::println);
```

Pick the collection

**Quiz:** You need to store unique user IDs and check membership quickly. Which type?

- [ ] ArrayList
- [x] HashSet
- [ ] LinkedList
- [ ] int[]

*Answer:* HashSet. HashSet gives O(1) average contains() and rejects duplicates automatically.
