Java Collections Framework
The Java Collections Framework provides standard interfaces and implementations for storing, retrieving, iterating, sorting, and organizing groups of objects.
What is a Collection?
A collection is an object that groups multiple elements together. Java provides standard interfaces so algorithms can work with groups of data without depending on one concrete implementation.
Map is part of the Java Collections Framework, but it does not extend the Collection interface.Main Interfaces
| Interface | Main property | Duplicates? | Typical use |
|---|---|---|---|
List | Ordered, index-based sequence | Yes | Shopping list, ordered records |
Set | Unique elements | No | Tags, unique IDs, membership tests |
Queue | Elements processed in an order | Usually yes | Tasks, requests, scheduling |
Deque | Insert/remove at both ends | Usually yes | Stacks, queues, sliding windows |
Map | Key-value associations | Keys: no | Indexes, dictionaries, lookup tables |
Common Implementations
ArrayList: dynamic array; fast indexed access and usually the default choice for a list.LinkedList: doubly linked list; also implementsDeque. It can add/remove efficiently at known positions such as the ends, but indexed access is slow.HashSet: hash-based set with fast average-case membership operations and no guaranteed iteration order.LinkedHashSet: preserves insertion order while enforcing uniqueness.TreeSet: sorted set based on a tree structure.HashMap: hash-based key-value map with fast average-case lookup.LinkedHashMap: preserves a predictable encounter order.TreeMap: sorted map ordered by keys.PriorityQueue: retrieves elements according to priority rather than insertion order.ArrayDeque: efficient general-purpose stack and queue implementation.
Which One Should You Use?
| Need | Good first choice | Reason |
|---|---|---|
| Indexed ordered data | ArrayList | Fast random access, compact storage |
| Unique unordered values | HashSet | Fast average lookup |
| Unique sorted values | TreeSet | Maintains sort order |
| Key-value lookup | HashMap | Fast average key lookup |
| Sorted keys | TreeMap | Keys remain ordered |
| FIFO queue | ArrayDeque | Efficient operations at both ends |
| Priority-based processing | PriorityQueue | Retrieves highest/lowest priority according to ordering |
Basic Examples
List<String> shoppingList = new ArrayList<>();
shoppingList.add("Milk");
shoppingList.add("Bread");
shoppingList.add("Milk"); // duplicate allowed
Set<String> hobbies = new HashSet<>();
hobbies.add("Reading");
hobbies.add("Swimming");
hobbies.add("Reading"); // duplicate ignored
Map<String, String> contacts = new HashMap<>();
contacts.put("Alice", "12345");
contacts.put("Bob", "67890");
Queue<String> bankLine = new ArrayDeque<>();
bankLine.offer("Customer1");
bankLine.offer("Customer2");
System.out.println(bankLine.poll()); // Customer1Iterating Through Collections
for (String name : shoppingList) {
System.out.println(name);
}You can also use an explicit iterator:
Iterator<String> it = shoppingList.iterator();
while (it.hasNext()) {
String item = it.next();
System.out.println(item);
}Sorting
List<String> names =
new ArrayList<>(List.of("Charlie", "Alice", "Bob"));
Collections.sort(names);Modern Java also supports comparator-based sorting:
names.sort(Comparator.reverseOrder());Natural Ordering vs Comparator
Comparable<T>defines a type's natural order usingcompareTo.Comparator<T>defines an external or alternative ordering usingcompare.
Immutability and Factory Methods
List<String> fixed = List.of("A", "B", "C");
Set<Integer> numbers = Set.of(1, 2, 3);
Map<String, Integer> scores =
Map.of("Alice", 90, "Bob", 85);These factory methods create unmodifiable collections. Attempts to add or remove elements cause an exception.
Useful Complexity Intuition
| Structure | Typical strength | Typical trade-off |
|---|---|---|
ArrayList | Fast indexed access | Middle insert/remove may shift elements |
LinkedList | Fast end operations when used as deque | Slow indexed access |
HashSet / HashMap | Fast average lookup | No sorted order |
TreeSet / TreeMap | Sorted data | Usually slower than hashing for pure lookup |
PriorityQueue | Fast access to priority element | Not a fully sorted iteration |
Common Mistakes
- Assuming
HashMaporHashSetpreserves insertion order. - Using
LinkedListfor frequent indexed access. - Modifying a collection during enhanced-for iteration without using the iterator correctly.
- Forgetting that mutable objects used as hash keys must have consistent
equalsandhashCode.
Conclusion
The Java Collections Framework gives you interchangeable data-structure interfaces with specialized implementations. Choose according to ordering, uniqueness, lookup, indexing, queue behavior, sorting, and mutation requirements rather than choosing a class only by familiarity.