Careeroza
Collections Overview
Why Collections?
Arrays have a fixed size and few features. The Collections Framework (java.util) gives ready-made, resizable data structures with methods to add, remove, search and sort.
Iterable
└── Collection
├── List (ordered, duplicates allowed) ArrayList, LinkedList
├── Set (no duplicates) HashSet, LinkedHashSet, TreeSet
└── Queue (processing order) PriorityQueue
└── Deque (both ends) ArrayDeque, LinkedList
Map (key -> value, not a Collection) HashMap, LinkedHashMap, TreeMapChoosing a Collection
| Need | Use | Why |
|---|---|---|
| Ordered list, fast access by index | ArrayList | array-backed, O(1) get |
| Unique items, fast lookup | HashSet | O(1) contains |
| Unique items, sorted | TreeSet | red-black tree, O(log n) |
| Key → value lookup | HashMap | O(1) get/put |
| Key → value in insertion order | LinkedHashMap | keeps order |
| Key → value sorted by key | TreeMap | sorted keys, range queries |
| Stack or queue | ArrayDeque | fast at both ends |
| Always take the smallest / highest priority | PriorityQueue | heap |
Tip: Declare variables with the interface type: List<String> names = new ArrayList<>();. Then you can change the implementation later without touching the rest of the code.
Immutable Factory Methods
Example
List.of, Set.of and Map.of (Java 9+) create small read-only collections.
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) {
List<String> days = List.of("Mon", "Tue", "Wed");
Set<Integer> primes = Set.of(2, 3, 5);
Map<String, Integer> pins = Map.of("Delhi", 110001, "Mumbai", 400001);
System.out.println(days + " size=" + days.size());
System.out.println("has 3? " + primes.contains(3));
System.out.println("Mumbai PIN: " + pins.get("Mumbai"));
try {
days.add("Thu");
} catch (UnsupportedOperationException e) {
System.out.println("List.of is read-only");
}
}
}Output
[Mon, Tue, Wed] size=3 has 3? true Mumbai PIN: 400001 List.of is read-only