Chapter 5: Collections
Introduction
Learning Outcomes
Explain the interfaces, implementations and algorithms of the collections framework and its interface/class hierarchy.
Write type-safe code with generic types such as List<String>; use wrapper classes and autoboxing.
Use ArrayList, LinkedList, Vector and Stack; explain their performance differences.
Build FIFO, priority and LIFO behavior with Queue, PriorityQueue and ArrayDeque.
Choose correctly among HashSet, TreeSet, HashMap, TreeMap and their linked versions.
Iterate safely with Iterator; sort, shuffle and search with Collections; build filter, map and reduce pipelines with java.util.stream.
The Collections Framework
Why Collections?
- Collection: a data structure that stores and manages several elements in a single object.
- Java Collections Framework: the ready-made interfaces, classes and algorithms in package
java.util. - Powerful, well-tested tools for storing, sorting, searching and processing data, optimized for performance and safety.
- Unlike an array, the size is dynamic, and methods such as
add,removeandcontainscome built in. - Picking the right structure matters: each collection type is designed for a different need.
Array: size fixed up front
int[] arr = new int[3]; // size fixed: 3 arr[0] = 10; arr[1] = 20; arr[2] = 30; // arr[3] = 40; → ArrayIndexOutOfBoundsException
List: grows as needed
List<Integer> list = new ArrayList<>(); list.add(10); list.add(20); list.add(30); list.add(40); // no problem: it grows System.out.println(list); System.out.println("size: " + list.size());
[10, 20, 30, 40] size: 4
ArrayList is a bus that grows as passengers board.The Collections Framework
Kinds of Collections
Ordered, indexed elements; duplicates allowed. ArrayList, LinkedList
Unique elements only; the same element is not added twice. HashSet, TreeSet
Key → value pairs; each key appears once. HashMap, TreeMap
Elements waiting to be processed; usually first in, first out (FIFO). LinkedList, PriorityQueue
The Collections Framework
Core Operations and Design Goals
Add, remove, update and search; easy iteration with a for-each loop.
A simple, clear API: code is easier to read and maintain.
Memory-efficient structures optimized for data volume and access patterns.
Generic types (List<String>) catch elements of the wrong type at compile time.
A family of classes for different needs, working smoothly with the rest of the standard library.
Sorting, searching and shuffling are built in; misuse is reported with exceptions. They save time and make software more reliable.
The Collections Framework
Collection Interfaces
Iterable: anything you can loop over withfor-each(theiterator()method).Collection: methods common to all collections (add,remove,size…).List,Queue,Set: subinterfaces that extendCollection.Map: a key–value structure. It is part of the framework but does not extendCollection.
The arrows follow UML: a hollow triangle points to the extended (parent) interface.
The Collections Framework
Collection Classes
LinkedList implements both List and Deque. Blue boxes are interfaces (behavior only); green boxes are classes you can instantiate with new.
The Collections Framework
Three Parts of the Framework
Defines how a data structure should behave (what it does). Example: List represents an ordered list.
The actual class that implements the interface (how it does it). Example: ArrayList implements List with a dynamic array.
Ready-made methods for operations such as sorting and searching. Example: Collections.sort() sorts a list.
List<String> list = new ArrayList<>(); // interface ← class list.add("Red"); list.add("Blue"); Collections.sort(list); // algorithm System.out.println(list);
[Blue, Red]
The Collections Framework
Programming to an Interface
- An interface defines a behavior; classes implement it with their own methods.
- Different kinds of storage:
ArrayListis a dynamic array,LinkedLista doubly linked list,HashMapa key–value table. - Each class meets the needs of a particular data structure and does a particular job.
- Declare variables and parameters with the interface type: the implementation can be swapped in one line, while the rest of the code and the basic behavior stay the same.
public class PrintList { // interface parameter: works with any List static void print(List<String> list) { for (String s : list) { System.out.print(s + " "); } System.out.println("(" + list.size() + " items)"); } public static void main(String[] args) { List<String> a = new ArrayList<>(); a.add("Apple"); a.add("Pear"); List<String> b = new LinkedList<>(a); // a copy b.add("Cherry"); print(a); print(b); } }
Apple Pear (2 items) Apple Pear Cherry (3 items)
The Collections Framework
Generic Types and Type Safety
List<String> names = new ArrayList<>(); names.add("Ali"); // names.add(42); // compile error String first = names.get(0); // no cast needed List<Integer> grades = new ArrayList<>(); // no List<int> grades.add(85); // boxing: int → Integer int n = grades.get(0); // unboxing → int System.out.println(first + " " + n);
Ali 85
- The element type goes inside
<>:List<String>means “list of String”. - A wrong type is caught at compile time; the result of
getneeds no cast. - The empty
<>on the right is the diamond operator (Java 7+); the type is inferred from the left side.
Collections hold objects only
| Primitive type | Wrapper class |
|---|---|
int | Integer |
double | Double |
char | Character |
boolean | Boolean |
long | Long |
Primitive types use wrapper classes. The conversion is automatic: autoboxing and unboxing.
The Collections Framework
First Examples
// list of names (ArrayList) List<String> nameList = new ArrayList<>(); nameList.add("Ahmet"); nameList.add("Ayşe"); System.out.println(nameList); // phone book (HashMap) Map<String, String> phoneBook = new HashMap<>(); phoneBook.put("Ahmet", "555-1234"); phoneBook.put("Ayşe", "555-9876"); System.out.println(phoneBook.get("Ahmet"));
[Ahmet, Ayşe] 555-1234
- List of names: an
ArrayListkeeps elements in insertion order;addappends to the end. - Phone book: a
HashMapmaps a key (the name) to a value (the number). - Add with
put(key, value); look up the value withget(key). - Printing a list with
printlnshows its elements inside[ … ].
The Collections Framework
Methods of the Collection Interface
| Method | Purpose | Returns |
|---|---|---|
add(E e) | adds the element | boolean: true if added |
remove(Object o) | removes the element | boolean |
size() | gives the number of elements | int |
isEmpty() | is the collection empty? | boolean |
contains(Object o) | is the element in the collection? | boolean |
containsAll(Collection<?> c) | are all elements of c in this collection? | boolean |
clear() | removes all elements | — |
toArray() | converts the collection to an array | Object[] |
iterator() | gives an iterator for traversal | Iterator<E> |
forEach(Consumer<? super E> a) | applies an action to each element (Java 8+) | — |
E: the element type (a generic type parameter). ? is a wildcard: “any type”. Every List, Set and Queue has these methods.
The Collections Framework
Collection Methods: Example
Collection<String> colors = new ArrayList<>();
colors.add("red");
colors.add("green");
colors.add("blue");
System.out.println(colors.size());
System.out.println(colors.contains("green"));
colors.remove("green");
System.out.println(colors);
Collection<String> wanted = Arrays.asList("blue", "red");
System.out.println(colors.containsAll(wanted));
Object[] arr = colors.toArray();
System.out.println(arr.length);
colors.clear();
System.out.println(colors.isEmpty());Output
3 true [red, blue] true 2 true
- The variable type is
Collection, so only the common methods are available (no indexedget). remove("green")removes the element by value.toArray()returns a new, copied array.
Lists
The List Interface
- Elements are kept in insertion order: ordered, but not sorted.
- Index-based access: the first element is at 0, the last at
size() − 1. - The same element may appear more than once.
ArrayList: a dynamic array with fast indexed access.LinkedList: a doubly linked list; fast insertion and removal at the ends.Vector: the old, synchronized (thread-safe) version; preferArrayList.
| Method | Purpose |
|---|---|
add(E e) | appends |
add(int i, E e) | inserts at position i |
get(int i) | gives the element at i |
set(int i, E e) | replaces the element at i |
remove(int i) | removes the element at i |
remove(Object o) | removes o |
indexOf(Object o) | first position; −1 if absent |
size() | number of elements |
Lists
The ArrayList Class
- Dynamic array: stores elements in an internal array, in insertion order.
- Extends
AbstractListand implements theListinterface. - Dynamic size: the internal array grows automatically when it fills up.
get(i)/set(i, e)are very fast: O(1).- Appending is fast on average; inserting or removing in the middle shifts elements, so it is slow: O(n).
ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Pear"); System.out.println(fruits.get(1)); // by index
Pear
Lists
How Does an ArrayList Grow?
Take a list created with new ArrayList<>(4), initial capacity 4: inside is a 4-cell array, 3 cells in use.
add("D"): there is a free cell; D goes straight to the end. Nothing moves: O(1).
add("E"): the array is full! A larger array is allocated and the 4 old elements are copied one by one: O(n).
E is written at index 4 of the new array. The old array is left to the garbage collector.
size(): size() is the number of occupied cells.Lists · Step-by-step code trace
ArrayList Methods: Trace
An empty ArrayList is created: size() is 0.
add appends the element: Ali is at index 0.
Four more elements are appended; indices 0…4.
The list is printed: elements in insertion order.
set(3, "Can"): Can replaces Deniz at index 3. The size does not change.
remove(4): Ece at index 4 is removed. It is the last element, so nothing shifts.
add(2, "Fatma"): Cem and Can each shift one place right; Fatma goes in at index 2.
indexOf("Banu") searches from the start and returns the first position: 1.
contains("Ece"): Ece was removed earlier, so the result is false.
Final size 5: 5 appends + 1 insertion − 1 removal.
ArrayList<String> names = new ArrayList<>(); names.add("Ali"); names.add("Banu"); names.add("Cem"); names.add("Deniz"); names.add("Ece"); System.out.println(names); names.set(3, "Can"); // replace index 3 System.out.println(names); names.remove(4); // remove index 4 System.out.println(names); names.add(2, "Fatma"); // insert at index 2 System.out.println(names); int index = names.indexOf("Banu"); System.out.println("index: " + index); boolean hasEce = names.contains("Ece"); System.out.println("has Ece: " + hasEce); System.out.println("size: " + names.size());
Lists
Inserting and Removing in the Middle
List<Integer> list2 = new ArrayList<>(Arrays.asList(10, 20, 30, 40)); list2.add(1, 15); // insert: 20, 30, 40 shift right System.out.println(list2); list2.remove(0); // remove first: all shift left System.out.println(list2);
Start: [10, 20, 30, 40]. Now add(1, 15) runs.
First the elements after index 1 shift one place right (starting from the end); cell 1 becomes free.
15 goes into the free cell. In a list of n elements the worst case is n shifts: O(n).
remove(0): 10 is removed and the 4 elements behind it shift one place left.
Result. Removing from the end needs no shifting: O(1). Removing from the front or middle is O(n).
[10, 15, 20, 30, 40] [15, 20, 30, 40]
Lists
The LinkedList Class
- Doubly linked list: elements live in nodes; each node holds its value and references to the previous (prev) and next (next) node.
- Extends
AbstractSequentialList; implements theListandDequeinterfaces. - Flexible size: there is no capacity; each insertion creates a new node and nothing is shifted.
- Insertion and removal at the ends are O(1); but
get(i)walks the nodes one by one: O(n).
Analogy: a line of people holding hands. If someone joins in the middle, only two people let go and regrab; but to find the 3rd person you must count from the start.
Lists
LinkedList Example
LinkedList<String> fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Pear"); fruits.addFirst("Cherry"); // add to front fruits.addLast("Banana"); // add to end System.out.println(fruits); System.out.println(fruits.getFirst()); System.out.println(fruits.getLast()); fruits.removeFirst(); System.out.println(fruits);
[Cherry, Apple, Pear, Banana] Cherry Banana [Apple, Pear, Banana]
| Method | Purpose |
|---|---|
addFirst(e) | adds to the front |
addLast(e) | appends |
getFirst() | gives the first element |
getLast() | gives the last element |
removeFirst() | removes and returns the first element |
removeLast() | removes and returns the last element |
These methods come from the Deque interface; add, get and remove(i) come from List.
Lists · Step-by-step code trace
LinkedList: Nodes and Links
Empty list: the first and last references are null. There is no such thing as capacity.
A node is created for Apple; the single node is both first and last.
Pear is linked at the end: Apple.next → Pear, Pear.prev → Apple; last is updated.
addFirst: Cherry goes to the front; only a few references change and nothing shifts: O(1).
addLast: Banana goes to the end, again O(1).
println walks the list from front to back along the next links.
getFirst(): the node first points to, Cherry.
getLast(): the node last points to, Banana. For an element in the middle (get(i)) you walk node by node.
removeFirst(): first moves to Apple and Apple.prev becomes null; the Cherry node drops out of the list.
[Apple, Pear, Banana] is printed.
LinkedList<String> fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Pear");
fruits.addFirst("Cherry");
fruits.addLast("Banana");
System.out.println(fruits);
System.out.println(fruits.getFirst());
System.out.println(fruits.getLast());
fruits.removeFirst();
System.out.println(fruits);Lists
ArrayList or LinkedList?
| Operation | ArrayList | LinkedList |
|---|---|---|
get(i), set(i, e) | O(1) | O(n): walks node by node |
Append add(e) | O(1) on average (occasional copy) | O(1) |
| Insert / remove at the front | O(n): every element shifts | O(1) |
| Insert / remove in the middle | O(n): shifting | O(n): find the position + O(1) relinking |
| Memory use | low: just the array | high: 2 extra references per node |
LinkedList (or ArrayDeque for a queue or stack).Lists
The Vector Class
- A growable dynamic array that implements the
Listinterface. - It starts with a given capacity (default 10) and doubles it when full.
- Its methods are synchronized: safe in multithreaded code, but every call pays for it.
- A leftover from Java 1.0; modern code prefers the lighter, faster
ArrayList.
Vector<Integer> v = new Vector<>(); // capacity: 10 for (int i = 1; i <= 11; i++) { v.addElement(i * 10); } System.out.println(v.size() + " / " + v.capacity()); System.out.println(v.elementAt(0)); v.removeElement(110); // value 110 System.out.println(v.size() + " / " + v.capacity());
11 / 20 10 10 / 20
Adding the 11th element raises the capacity from 10 to 20. Removal does not shrink it.
addElement(E obj) | elementAt(int i) | removeElement(Object obj) | size() | capacity() |
|---|---|---|---|---|
| adds an element | gives the element at i | removes the element | number of elements | current capacity |
Lists
The Stack Class
- LIFO (Last In, First Out): the last element in is the first out.
- The newest element sits on top, the oldest at the bottom (base).
- It extends the
Vectorclass. - Uses: undo, parsing text and expressions (bracket matching), depth-first search, the method call stack.
- Modern code should use
ArrayDeque(orLinkedList), which implements theDequeinterface.
Analogy: a pile of plates; you always take from and put on the top.
| Method | Purpose |
|---|---|
push(E item) | pushes onto the top |
pop() | removes and returns the top |
peek() | returns the top without removing it |
empty() | is the stack empty? |
search(Object o) | 1-based position from the top; −1 if absent |
Lists · Step-by-step code trace
Stack: Trace
An empty stack is created.
push("A"): A goes on top.
push("B"): B on top of A.
push("C"): now C is on top.
println prints the elements bottom to top: [A, B, C].
peek() returns the top element (C) without removing it.
pop() removes and returns C: last in, first out.
search("A") counts positions from the top, starting at 1: B is 1, A is 2.
empty(): the stack holds 2 elements, so the result is false.
Stack<String> stack = new Stack<>();
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println(stack);
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.search("A"));
System.out.println(stack.empty());Lists
Iterating Over a List
List<String> courses = new ArrayList<>( Arrays.asList("Physics", "Java", "Circuits")); // 1) indexed for for (int i = 0; i < courses.size(); i++) { System.out.print(courses.get(i) + " "); } System.out.println(); // 2) enhanced for (for-each) for (String d : courses) { System.out.print(d + " "); } System.out.println(); // 3) forEach + lambda (Java 8+) courses.forEach(d -> System.out.print(d + " ")); System.out.println();
Output
Physics Java Circuits Physics Java Circuits Physics Java Circuits
- Indexed for: when you need the index (lists only).
- for-each: the most readable way; works for every collection.
- forEach + lambda: concise Java 8+ form.
- If you must remove elements while iterating, use an
Iterator.
Queues
The Queue Interface
- FIFO (First-In-First-Out): the first element in is the first out.
- Elements leave in the order they arrived; new elements join at the tail, and the next one to process is taken from the head.
- Elements are usually handled with
offer,pollandpeek. - Implementations:
LinkedList(doubly linked list),PriorityQueue(by priority, not FIFO),ArrayDeque(dynamic array). - Uses: print queues, task queues, breadth-first search.
Analogy: a supermarket checkout. You join at the back; the person at the front pays.
| Operation | Throws exception | Returns special value |
|---|---|---|
| Insert (at tail) | add(e) | offer(e) → false |
| Remove (from head) | remove() | poll() → null |
| Examine (head) | element() | peek() → null |
On an empty queue remove() and element() throw NoSuchElementException, while poll() and peek() return null. size(): number of elements.
Queues · Step-by-step code trace
Queue: Trace
The variable has type Queue; the object is a LinkedList.
offer("Ali"): Ali joins the queue; he is both head and tail.
Banu joins at the tail.
Cem joins at the tail.
The queue is printed head to tail.
peek() returns the head without removing it.
poll() removes and returns the head: Ali, first in, is first out.
Next, Banu leaves.
size(): 1 element left in the queue.
Cem leaves too; the queue is empty.
On an empty queue poll() does not fail; it returns null.
Queue<String> queue = new LinkedList<>();
queue.offer("Ali");
queue.offer("Banu");
queue.offer("Cem");
System.out.println(queue);
System.out.println(queue.peek());
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.size());
System.out.println(queue.poll());
System.out.println(queue.poll());Queues
The PriorityQueue Class
- Priority queue: the element that leaves is always the highest-priority one, not the earliest added.
- The default priority is natural order: the smallest element leaves first. Pass a comparator for the reverse.
- Elements must be comparable (
Comparable), or aComparatormust be supplied. - Internally a binary heap:
add/pollO(log n),peekO(1); grows dynamically. - Uses: task scheduling, emergency-room triage, shortest-path algorithms.
| Method | Purpose |
|---|---|
add(E e) | adds an element |
poll() | removes and returns the highest-priority element |
peek() | returns the highest-priority element without removing it |
remove(Object o) | removes the given element |
size() | number of elements |
Queues
PriorityQueue Example
PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.add(30); pq.add(10); pq.add(40); pq.add(20); System.out.println(pq.peek()); // smallest System.out.println(pq); // heap order while (!pq.isEmpty()) { System.out.print(pq.poll() + " "); } System.out.println();
10 [10, 20, 40, 30] 10 20 30 40
println(pq) is not sorted: the internal array only obeys “every parent is smaller than its children”. To get sorted output, remove elements one by one with poll.
Queues · Step-by-step code trace
PriorityQueue: The Heap Rule Step by Step
Inside, an empty array: a binary heap. Rule: every parent is less than or equal to its children.
30 goes to the root (index 0).
10 is appended (index 1); it is smaller than its parent 30, so it moves up and they swap. The root is now 10.
40 goes to index 2; it is larger than its parent 10 and stays.
20 goes to index 3; smaller than its parent 30 → swap; larger than 10 → stop.
peek(): the root, i.e. the smallest element: 10. The queue is unchanged; O(1).
println prints the internal array as is: [10, 20, 40, 30] is not sorted.
poll(): the root 10 leaves; the last element, 30, moves to the root and swaps with its smaller child 20, sinking down.
20 leaves; 40 moves to the root and swaps with 30.
30 leaves; only 40 is left.
40 leaves; the queue is empty and the loop ends. They came out sorted: 10 20 30 40.
A newline is printed. Each poll follows only one branch: O(log n).
PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.add(30); pq.add(10); pq.add(40); pq.add(20); System.out.println(pq.peek()); System.out.println(pq); while (!pq.isEmpty()) { System.out.print(pq.poll() + " "); } System.out.println();
Queues
Setting the Priority
class Task implements Comparable<Task> { String name; int priority; // smaller = more urgent Task(String name, int priority) { this.name = name; this.priority = priority; } @Override public int compareTo(Task o) { return Integer.compare(priority, o.priority); } @Override public String toString() { return name + "(" + priority + ")"; } }
If compareTo returns a negative number, this comes first. Collections.reverseOrder() reverses natural order: the largest leaves first.
PriorityQueue<Task> tasks =
new PriorityQueue<>();
tasks.add(new Task("Report", 3));
tasks.add(new Task("Outage", 1));
tasks.add(new Task("Meeting", 2));
while (!tasks.isEmpty()) {
System.out.println(tasks.poll());
}Outage(1) Meeting(2) Report(3)
PriorityQueue<Integer> maxFirst =
new PriorityQueue<>(
Collections.reverseOrder());
maxFirst.add(30);
maxFirst.add(10);
maxFirst.add(40);
System.out.println(maxFirst.poll());40
Queues
The Deque Interface
- Deque (double-ended queue, pronounced “deck”): a queue where elements can be added and removed at both ends.
- It combines
Queue(FIFO) andStack(LIFO) behavior. - Implementations:
LinkedList(doubly linked list) andArrayDeque(dynamic array).
| Head | Purpose | Tail | Purpose |
|---|---|---|---|
addFirst(e) | adds to the front | addLast(e) | appends |
removeFirst() | removes and returns the head | removeLast() | removes and returns the tail |
getFirst() | returns the head | getLast() | returns the tail |
remove…/get… throw on an empty deque; poll…/peek… return null. size(): number of elements.
Queues
The ArrayDeque Class
- Implements a double-ended queue with a dynamic (circular) array.
- Supports both queue and stack operations.
- Usually faster and lighter than
LinkedListandStack; the recommended class for stacks and queues. - Does not accept
nullelements.
| Method | Purpose |
|---|---|
pollFirst() / pollLast() | removes and returns the head / tail |
peekFirst() / peekLast() | returns the head / tail without removing it |
As a stack (instead of Stack)
Deque<String> stack = new ArrayDeque<>(); stack.push("A"); // adds at the front stack.push("B"); System.out.println(stack.pop());
B
push/pop/peek work at the head. As a queue: offer adds at the tail, poll takes from the head.
Queues · Step-by-step code trace
ArrayDeque: Trace
An empty ArrayDeque.
addFirst(5): 5 goes to the front (the only element).
addLast(10): 10 goes to the end.
addFirst(1): 1 goes to the front; 5 and 10 stay in place.
Printed from head to tail.
pollFirst() removes the 1 at the head; it is unboxed into an int.
pollLast() removes the 10 at the tail.
Both values are printed.
peekFirst() returns the 5 at the head without removing it.
ArrayDeque<Integer> numbers = new ArrayDeque<>(); numbers.addFirst(5); numbers.addLast(10); numbers.addFirst(1); System.out.println(numbers); int firstNum = numbers.pollFirst(); int lastNum = numbers.pollLast(); System.out.println(firstNum + " " + lastNum); System.out.println(numbers.peekFirst());
Sets
The Set Interface
- Stores unique elements; like a set in mathematics, and suited to set operations.
- Each element appears only once:
adddoes not add an existing element and returnsfalse. - In general there is no order guarantee (the order depends on the implementation).
- Insertion, removal and lookup are fast.
HashSet: no order.LinkedHashSet: insertion order.TreeSet: sorted (natural order or aComparator).
| Method | Purpose |
|---|---|
add(E e) | adds to the set |
remove(Object o) | removes from the set |
contains(Object o) | is it in the set? |
size() | number of elements |
Set<String> fruits = new HashSet<>();
System.out.println(fruits.add("Apple"));
System.out.println(fruits.add("Pear"));
System.out.println(fruits.add("Apple"));
System.out.println(fruits.size());
System.out.println(fruits.contains("Pear"));
fruits.remove("Pear");
System.out.println(fruits);true true false 2 true [Apple]
Sets
HashSet and Hashing
- Stores unique elements without order; extends
AbstractSetand implementsSet. - A bucket number is computed from the element’s
hashCode(), and the element goes straight into that bucket: insertion and lookup are O(1) on average. - Storage order is not guaranteed: iteration follows the buckets.
Inside is a table of 16 buckets (it grows as it fills).
add("salt"): bucket 3 is computed from the hash, and salt goes there.
add("egg"): bucket 4.
add("milk"): bucket 8.
The second add("egg"): bucket 4 already holds an element that is equals to it. It is not added; add returns false.
add("coffee"): bucket 7. Iteration order follows the buckets: [salt, egg, coffee, milk].
Sets
The LinkedHashSet Class
- A set of unique elements; extends
HashSet. - It also links the elements in a linked list: insertion order is preserved.
- It gives fast access and guarantees that elements are unique.
- Choose it when both performance and order matter; if order does not matter and performance is critical, use
HashSet.
LinkedHashSet<Integer> numbers =
new LinkedHashSet<>();
numbers.add(5);
numbers.add(10);
numbers.add(5); // duplicate: not added
numbers.add(1);
System.out.println(numbers);[5, 10, 1]
| Method | Purpose |
|---|---|
add(E e) | adds an element |
remove(Object o) | removes the element |
contains(Object o) | is the element present? |
size() | number of elements |
clear() | removes all elements |
Sets
Order in Three Sets
String[] words = {"salt", "egg", "milk", "egg", "coffee"};
Set<String> h = new HashSet<>();
Set<String> l = new LinkedHashSet<>();
Set<String> t = new TreeSet<>();
for (String k : words) {
h.add(k);
l.add(k);
t.add(k);
}
System.out.println("HashSet: " + h);
System.out.println("LinkedHashSet: " + l);
System.out.println("TreeSet: " + t);HashSet: [salt, egg, coffee, milk] LinkedHashSet: [salt, egg, milk, coffee] TreeSet: [coffee, egg, milk, salt]
| Class | Iteration order | Underlying structure | add / contains |
|---|---|---|---|
HashSet | no guarantee (bucket order) | hash table | O(1) average |
LinkedHashSet | insertion order | hash table + linked list | O(1) average |
TreeSet | sorted (ascending) | red-black tree | O(log n) |
Sets
Our Own Classes in a HashSet
class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (!(o instanceof Point)) return false; Point n = (Point) o; return x == n.x && y == n.y; } @Override public int hashCode() { return Objects.hash(x, y); } }
PointA: the same class without equals/hashCode
Set<PointA> s1 = new HashSet<>(); s1.add(new PointA(1, 2)); s1.add(new PointA(1, 2)); System.out.println(s1.size()); Set<Point> s2 = new HashSet<>(); s2.add(new Point(1, 2)); s2.add(new Point(1, 2)); System.out.println(s2.size());
2 1
PointA: the two objects count as different (Object’sequalscompares references) → size 2.Point:equalsandhashCodeare overridden → the same point appears once → size 1.
Rule: equal objects must have equal hashCode values: the bucket is found with hashCode, then compared with equals.
Sets · Step-by-step code trace
Changing an Object Inside a Set: The Lost Element
HashSet uses a 16-bucket hash table internally. Point’s equals and hashCode are computed from x and y.
Objects.hash(1, 2) = 994. The bucket number is the last 4 bits of the hash: 994 → bucket 2.
add(p): the object lands in bucket 2.
contains(p): bucket 2 is checked again and equals is true → true.
A field of the object in the set has changed! Its hashCode is now 1118 → bucket 14. But the object still sits in bucket 2.
contains(p): bucket 14 is checked; it is empty → false. The object is in the set but cannot be found.
The new Point(1, 2) goes to bucket 2; the object there is now (5, 2), so equals is false → false.
add(p): bucket 14 looks empty, so the same object is added a second time.
size() = 2: the set is corrupted. Never change the fields used by equals/hashCode of an object in a hashed collection; choose immutable keys such as String or Integer.
Set<Point> set = new HashSet<>(); Point p = new Point(1, 2); set.add(p); System.out.println(set.contains(p)); p.x = 5; // field changed System.out.println(set.contains(p)); System.out.println(set.contains(new Point(1, 2))); set.add(p); System.out.println(set.size());
Sets
SortedSet and TreeSet
SortedSet: the interface of a set that keeps its unique elements sorted.- Sorting follows natural order (
Comparable) or a suppliedComparator. - It offers subset and superset operations.
TreeSet: extendsAbstractSetand implementsNavigableSet(and thereforeSortedSet).- Internally a red-black tree: insertion, removal and lookup are O(log n).
| Method | Purpose |
|---|---|
first() / last() | smallest / largest element |
headSet(to) | elements less than to (to excluded) |
tailSet(from) | from and greater (from included) |
subSet(from, to) | from included, to excluded |
comparator() | the sorting Comparator; null for natural order |
add, remove | insertion, removal |
Sets
TreeSet Example
TreeSet<Integer> grades = new TreeSet<>(); grades.add(70); grades.add(50); grades.add(90); grades.add(60); grades.add(80); System.out.println(grades); System.out.println(grades.first() + " " + grades.last()); System.out.println(grades.headSet(70)); // 70 excluded System.out.println(grades.tailSet(70)); // 70 included System.out.println(grades.subSet(60, 90)); // [60, 90) System.out.println(grades.comparator()); // natural order
TreeSet<String> fruits = new TreeSet<>();
fruits.add("Pear");
fruits.add("Apple");
System.out.println(fruits);Output
[50, 60, 70, 80, 90] 50 90 [50, 60] [70, 80, 90] [60, 70, 80] null [Apple, Pear]
Elements are kept sorted whatever order they are added in. Strings are ordered alphabetically (by character code).
Sets
Set Operations
Set<Integer> a = new TreeSet<>(Arrays.asList(1, 2, 3, 4)); Set<Integer> b = new TreeSet<>(Arrays.asList(3, 4, 5)); Set<Integer> union = new TreeSet<>(a); union.addAll(b); Set<Integer> inter = new TreeSet<>(a); inter.retainAll(b); Set<Integer> diff = new TreeSet<>(a); diff.removeAll(b); System.out.println("A ∪ B = " + union); System.out.println("A ∩ B = " + inter); System.out.println("A − B = " + diff); System.out.println(a.containsAll(inter));
A ∪ B = [1, 2, 3, 4, 5] A ∩ B = [3, 4] A − B = [1, 2] true
| Operation | Method |
|---|---|
| union ∪ | addAll |
| intersection ∩ | retainAll |
| difference − | removeAll |
| subset ⊆ | containsAll |
These methods modify the set they are called on, so make a copy first.
Maps
The Map Interface
- Stores key–value pairs: each key maps to one value.
- Keys are unique; values may repeat.
- Gives fast access by key and lets you work on the pairs.
HashMap: no order guarantee.LinkedHashMap: insertion order.TreeMap: sorted keys (natural order or aComparator).
Analogy: a dictionary. You find the meaning (value) by the word (key); the same word does not appear twice.
Maps
Map Methods
| Method | Purpose |
|---|---|
put(K key, V value) | maps the key to the value; if the key exists, replaces the value and returns the old one |
get(Object key) | returns the key’s value; null if the key is absent |
remove(Object key) | removes the key and its value |
containsKey(Object key) | is the key in the map? |
containsValue(Object v) | is the value in the map? |
keySet() | returns all keys as a Set |
values() | returns all values as a Collection |
entrySet() | returns all key–value pairs as a Set<Map.Entry<K, V>> |
size(), isEmpty() | number of pairs, is it empty? |
getOrDefault(key, v) | returns v if the key is absent (Java 8+) |
K: key type, V: value type. Example: Map<String, Integer> maps names to grades.
Maps
The HashMap Class
HashMap<String, Double> prices = new HashMap<>();
prices.put("Tablet", 2000.0);
prices.put("Headphones", 350.0);
prices.put("Case", 120.0);
Double old = prices.put("Tablet", 1800.0);
System.out.println(old);
System.out.println(prices.get("Tablet"));
System.out.println(prices.get("Laptop"));
System.out.println(prices.containsKey("Case"));
prices.remove("Case");
System.out.println(prices.size());2000.0 1800.0 null true 2
prices.put(null, 0.0); // a single null key prices.put("Pen", null); // null value System.out.println(prices.size());
4
- Stores key–value pairs in a hash table:
get/putare O(1) on average. - Extends
AbstractMapand implementsMap. - Unique keys:
putwith an existing key replaces the value. - Null: allows one
nullkey and any number ofnullvalues. - Elements are stored without order.
Maps
Iterating Over a Map
Map<String, Integer> grades = new TreeMap<>(); grades.put("Cem", 72); grades.put("Ayşe", 95); grades.put("Banu", 60); for (String name : grades.keySet()) { System.out.print(name + " "); } System.out.println(); for (Integer g : grades.values()) { System.out.print(g + " "); } System.out.println(); for (Map.Entry<String, Integer> g : grades.entrySet()) { System.out.println(g.getKey() + " → " + g.getValue()); }
Ayşe Banu Cem 95 60 72 Ayşe → 95 Banu → 60 Cem → 72
keySet(): keys only.values(): values only.entrySet(): each pair is aMap.Entry, read withgetKey()andgetValue(). The most efficient way when you need both key and value.- A
Mapcannot be given directly tofor-each: it is notIterable.
Maps · Step-by-step code trace
Counting Words: Trace
The text and an empty TreeMap are set up. split(" ") breaks the text into words.
"egg" is seen for the first time: put(k, 1).
"coffee" is seen for the first time: put(k, 1).
"egg" is already there: the old value 1 is read and 2 is stored.
"milk" is seen for the first time: put(k, 1).
"coffee" is already there: the old value 1 is read and 2 is stored.
"egg" is already there: the old value 2 is read and 3 is stored.
The loop is done. A TreeMap prints its keys in alphabetical order.
String text = "egg coffee egg milk coffee egg"; Map<String, Integer> counter = new TreeMap<>(); for (String k : text.split(" ")) { if (counter.containsKey(k)) { counter.put(k, counter.get(k) + 1); } else { counter.put(k, 1); } } System.out.println(counter);
Maps
The LinkedHashMap Class
- A map of unique key–value pairs; extends
HashMap. - Each entry is a key and a value; keys are unique.
- It links the pairs in a linked list: insertion order is preserved.
- Choose it when performance and order both matter; if order does not matter,
HashMapis enough.
Map<String, String> contacts = new LinkedHashMap<>(); contacts.put("Zeynep", "555-1111"); contacts.put("Ahmet", "555-1234"); contacts.put("Mert", "555-2222"); Map<String, String> h = new HashMap<>(contacts); Map<String, String> t = new TreeMap<>(contacts); System.out.println("LinkedHashMap: " + contacts); System.out.println("HashMap: " + h); System.out.println("TreeMap: " + t);
LinkedHashMap: {Zeynep=555-1111, Ahmet=555-1234, Mert=555-2222}
HashMap: {Ahmet=555-1234, Mert=555-2222, Zeynep=555-1111}
TreeMap: {Ahmet=555-1234, Mert=555-2222, Zeynep=555-1111}The core methods are the same as in Map: put, remove, get, containsKey, size.
Maps
The Hashtable Class
- An old, synchronized (thread-safe) map class for key–value pairs (Java 1.0).
- Difference from
HashMap:HashMapis not synchronized; everyHashtablemethod takes a lock. - Neither keys nor values may be
null. - Locking makes it slower than modern alternatives; use
HashMapin single-threaded code andConcurrentHashMapin multithreaded code. - Methods:
put,remove,get,containsKey,size.
Hashtable<String, String> phoneBook = new Hashtable<>(); phoneBook.put("Ahmet", "555-1234"); System.out.println(phoneBook.get("Ahmet")); System.out.println(phoneBook.containsKey("Ayşe")); // phoneBook.put(null, "x"); → NullPointerException
555-1234 false
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.hashCode()" because "key" is null
Maps
SortedMap and TreeMap
SortedMap: the interface of a map that keeps its keys sorted; each key appears once.- It offers submap operations such as head and tail maps.
TreeMap: extendsAbstractMapand implementsNavigableMap.- Keys are ordered by natural order or a supplied
Comparator. - Internally a red-black tree:
get/putO(log n).
| Method | Purpose |
|---|---|
firstKey() / lastKey() | smallest / largest key |
headMap(to) | keys less than to (excluded) |
tailMap(from) | from and greater (included) |
subMap(from, to) | from included, to excluded |
comparator() | the sorting Comparator (null for natural order) |
put, get, remove | same as Map |
Maps
TreeMap Example
TreeMap<String, Double> prices = new TreeMap<>();
prices.put("Tablet", 2000.0);
prices.put("Pen", 15.0);
prices.put("Notebook", 40.0);
prices.put("Ruler", 5.0);
System.out.println(prices);
System.out.println(prices.firstKey());
System.out.println(prices.lastKey());
System.out.println(prices.headMap("Pen"));
System.out.println(prices.tailMap("Pen"));
System.out.println(prices.subMap("Notebook", "Ruler"));Output
{Notebook=40.0, Pen=15.0, Ruler=5.0, Tablet=2000.0}
Notebook
Tablet
{Notebook=40.0}
{Pen=15.0, Ruler=5.0, Tablet=2000.0}
{Notebook=40.0, Pen=15.0}Maps
Comparing Map Classes
| HashMap | LinkedHashMap | TreeMap | Hashtable | |
|---|---|---|---|---|
| Iteration order | no guarantee | insertion order | sorted keys | no guarantee |
get / put | O(1) average | O(1) average | O(log n) | O(1) average, locked |
null key | one | one | no | no |
null value | yes | yes | yes | no |
| Synchronized | no | no | no | yes (legacy) |
| When? | the default choice | order must be kept | sorted keys, range queries | legacy code |
HashSet, LinkedHashSet and TreeSet use a HashMap, LinkedHashMap and TreeMap internally.Iterators
Iterator
- Iterator: an object for visiting the elements of a collection one by one.
- It reaches every element without knowing the collection’s internal structure (array, tree, hash table…).
- The safe way to remove while iterating is the iterator’s
remove()(orremoveIffor bulk removal). - A
for-eachloop uses anIteratorbehind the scenes. - For lists,
ListIteratorcan also move backwards and supportsaddandset.
| Method | Purpose |
|---|---|
hasNext() | is there a next element? |
next() | returns the next element and advances the cursor |
remove() | removes the element returned by the last next() |
Usually used in a while (it.hasNext()) loop (or a for).
Iterators · Step-by-step code trace
Iterator: Trace
The list is set up: [3, 8, 5].
iterator(): the cursor is placed before the first element.
hasNext() is true; next() returns 3 and advances the cursor.
The element is printed.
hasNext() is true; next() returns 8 and advances the cursor.
The element is printed.
hasNext() is true; next() returns 5 and advances the cursor.
The element is printed.
The cursor is at the end: hasNext() is false and the loop ends.
ArrayList<Integer> list = new ArrayList<>(); list.add(3); list.add(8); list.add(5); Iterator<Integer> iterator = list.iterator(); while (iterator.hasNext()) { Integer num = iterator.next(); // process the element here System.out.println(num); }
Iterators
Removing While Iterating
Wrong: removing from the collection inside for-each
List<Integer> numbers = new ArrayList<>(Arrays.asList(4, 7, 10, 13, 16)); for (Integer s : numbers) { if (s % 2 == 0) { numbers.remove(s); } }
Exception in thread "main" java.util.ConcurrentModificationException
Right: Iterator.remove()
List<Integer> numbers = new ArrayList<>(); Collections.addAll(numbers, 4, 7, 10, 13, 16); Iterator<Integer> it = numbers.iterator(); while (it.hasNext()) { if (it.next() % 2 == 0) { it.remove(); // safe removal } } System.out.println(numbers);
Shortcut (Java 8+)
List<Integer> s2 = new ArrayList<>();
Collections.addAll(s2, 4, 7, 10, 13, 16);
s2.removeIf(s -> s % 2 == 0);
System.out.println(s2);[7, 13]
Both ways print the same: only the odd numbers remain.
Iterators · Step-by-step code trace
Removing Inside for-each: Why the Exception?
The list has 3 elements; modCount (the structural modification counter) is 0.
for-each secretly calls s.iterator(): cursor = 0, and the iterator saves the current modCount: expectedModCount = 0.
hasNext(): cursor (0) ≠ size (3) → true.
next(): first the counters are compared (0 = 0); x = 6, cursor = 1.
6 is even.
s.remove(x) is the list’s own method: 9 and 12 shift left, size becomes 2, modCount becomes 1. The iterator does not know.
hasNext(): cursor (1) ≠ size (2) → true; the loop goes on.
next(): modCount (1) ≠ expectedModCount (0) → ConcurrentModificationException. With {6, 9}, hasNext would be false: no exception, and 9 would go unchecked.
List<Integer> s = new ArrayList<>(); Collections.addAll(s, 6, 9, 12); for (Integer x : s) { // hidden Iterator if (x % 2 == 0) { s.remove(x); } } System.out.println(s);
The fail-fast check is best-effort, not a guarantee: never rely on the exception.
Algorithms
The Collections Class and Algorithms
Collectionis an interface;Collections(with an s) is a utility class of ready-madestaticmethods that work on collections.- These algorithms are fast and well tested; use them instead of hand-written loops.
- Choosing the right algorithm has a big impact on performance.
sort, reverse, reverseOrder
shuffle
binarySearch, max, min, frequency
copy, fill, swap, reverse
Algorithms
Sorting Methods
List<String> names = new ArrayList<>(
Arrays.asList("Cem", "Ayşe", "Banu", "Ali"));
Collections.sort(names);
System.out.println(names);
Collections.sort(names, Collections.reverseOrder());
System.out.println(names);
Collections.reverse(names);
System.out.println(names);[Ali, Ayşe, Banu, Cem] [Cem, Banu, Ayşe, Ali] [Ali, Ayşe, Banu, Cem]
| Method | Purpose |
|---|---|
sort(list) | by natural order; elements must be Comparable |
sort(list, c) | by the given Comparator |
reverse(list) | reverses the order of the list |
Classes such as String, Integer and Double are already Comparable. Java 8+: list.sort(null) also sorts by natural order.
Collections.sort: TimSort, O(n log n), stable (equal elements keep their order); Arrays.sort on primitives uses Dual-Pivot Quicksort.
Algorithms
Comparable: Natural Order
class Student implements Comparable<Student> { String name; int score; Student(String name, int score) { this.name = name; this.score = score; } // ascending by score @Override public int compareTo(Student other) { return Integer.compare(score, other.score); } @Override public String toString() { return name + ":" + score; } }
List<Student> roster = new ArrayList<>(); roster.add(new Student("Cem", 72)); roster.add(new Student("Ayşe", 95)); roster.add(new Student("Banu", 60)); Collections.sort(roster); System.out.println(roster);
[Banu:60, Cem:72, Ayşe:95]
- The class implements
Comparable<Student>and writescompareTo. - Result: negative →
thisfirst; 0 → equal; positive →otherfirst. Integer.compareis safer than subtraction (score − other.score): no overflow.
Algorithms
Comparator: Another Order
Collections.sort(roster, new Comparator<Student>() { @Override public int compare(Student a, Student b) { return a.name.compareTo(b.name); // by name } }); System.out.println(roster); // Java 8+: the same, shorter roster.sort(Comparator.comparing(o -> o.score)); System.out.println(roster);
[Ayşe:95, Banu:60, Cem:72] [Banu:60, Cem:72, Ayşe:95]
Comparator: a separate ordering written outside the class; a class can have several.- Classic form: an anonymous inner class with
compare(a, b). - Java 8+: one line with
Comparator.comparing(…)and a lambda;.reversed()for reverse order. - The natural order (
compareTo) does not change; another key is used for that sort only.
Algorithms
Shuffling
- Used to put the elements of a collection in random order.
Collections.shuffle(list)uses the Fisher–Yates (Knuth) algorithm: starting from the end of the list, it swaps each element with a randomly chosen one.- Fast: n − 1 swaps, O(n). Every possible ordering is equally likely (a uniform distribution).
- Uses: dealing cards, drawing lots, randomizing question order.
List<String> students = new ArrayList<>(
Arrays.asList("Ali", "Banu", "Cem", "Deniz"));
Collections.shuffle(students);
System.out.println(students);Output of one run
[Cem, Ali, Deniz, Banu]
The output differs on every run. For a reproducible shuffle (in tests), pass a seeded new Random(42) as the second argument.
Algorithms
Lottery Example
public class Lottery { // draws lottery numbers public static Integer[] draw(int total, int count) { ArrayList<Integer> numbers = new ArrayList<Integer>(); for (int i = 0; i < total; i++) { numbers.add(i + 1); // 1 … total } Collections.shuffle(numbers); // shuffle Integer[] drawn = new Integer[count]; for (int i = 0; i < count; i++) { drawn[i] = numbers.get(i); } return drawn; } public static void main(String[] args) { Integer[] result = draw(49, 6); // 6 out of 49 for (Integer item : result) { System.out.print(item + " "); } } }
Sample output
46 18 22 11 20 10
The list 1–49 is shuffled and the first 6 elements are taken: the numbers never repeat. The output differs on every run.
Algorithms
Searching Algorithms
Checks the elements one by one from start to end. No sorting required; good for small collections. O(n). Examples: indexOf, contains.
Checks the middle of a sorted collection, then goes left or right; each step halves the range. O(log n). The collection must be sorted.
List<Integer> numbers = Arrays.asList(1, 3, 5, 7, 9, 11);
System.out.println(Collections.binarySearch(numbers, 7));
System.out.println(Collections.binarySearch(numbers, 6));
System.out.println(numbers.indexOf(7)); // linear search3 -4 3
7 is found at index 3 in three comparisons. 6 is absent; its insertion point is 3, so the result is −(3) − 1 = −4.
Algorithms
Composition Algorithms
| Method | Purpose |
|---|---|
copy(target, source) | copies the source elements to the start of the target; requires target.size() ≥ source.size() |
fill(list, d) | sets every element to d |
reverse(list) | reverses the order of the elements |
swap(list, i, j) | swaps positions i and j |
max / min | largest / smallest element |
frequency(c, o) | how many times o occurs |
List<Integer> n = Arrays.asList(4, 9, 2, 9, 5); System.out.println(Collections.max(n)); System.out.println(Collections.min(n)); System.out.println(Collections.frequency(n, 9));
9 2 2
If the target is too short, copy throws IndexOutOfBoundsException: Source does not fit in dest.
Algorithms · Step-by-step code trace
Composition: Trace
Arrays.asList is a fixed-size list; target is a 4-element ArrayList.
copy: the 3 elements are written to positions 0–2 of the target; W stays.
reverse: the order flips.
swap(target, 0, 2): positions 0 and 2 trade places.
fill: every element becomes "Java". The size does not change.
List<String> names =
Arrays.asList("Ahmet", "Ayşe", "Cem");
List<String> target = new ArrayList<>(
Arrays.asList("X", "Y", "Z", "W"));
Collections.copy(target, names);
System.out.println(target);
Collections.reverse(target);
System.out.println(target);
Collections.swap(target, 0, 2);
System.out.println(target);
Collections.fill(target, "Java");
System.out.println(target);The Stream API
The Stream API (java.util.stream)
java.util.stream, new in Java 8, processes a sequence of data as a pipeline: we say “what to do”, and the library builds the loop.- A stream here is not an I/O stream like
InputStream: it stores no data, passes over a source (a list, an array, lines of a file) and does not modify the source.
List<Integer> grades = Arrays.asList(45, 82, 67, 90, 38, 75);
List<Integer> passed = grades.stream()
.filter(n -> n >= 50)
.map(n -> n + 5)
.sorted()
.collect(Collectors.toList());
System.out.println(passed);[72, 80, 87, 95]
From Java 16 on, the last line can be shortened to .toList(). Imports needed: java.util.*, java.util.stream.Collectors.
The Stream API
Intermediate and Terminal Operations
| Intermediate | Purpose |
|---|---|
filter(p) | passes elements that satisfy the condition |
map(f) | transforms each element |
flatMap(f) | flattens nested streams |
sorted() | sorts (waits for all elements) |
distinct() | drops duplicates (equals) |
limit(n) / skip(n) | takes / skips the first n elements |
peek(f) | observes elements (debugging) |
| Terminal | Result |
|---|---|
collect(...) | list, set, map… |
forEach(f) | an action for each element |
count() | number of elements (long) |
reduce(...) | reduces the elements to one value |
findFirst() | first element (Optional) |
anyMatch / allMatch / noneMatch | boolean |
min / max | Optional |
The Stream API
Lazy Evaluation and Single Use
List<String> names =
Arrays.asList("Arda", "Ece", "Ayşe", "Can");
Stream<String> pipe = names.stream()
.filter(s -> s.startsWith("A"))
.map(String::toUpperCase);
// nothing processed yet.
List<String> result =
pipe.collect(Collectors.toList());
System.out.println(result); // [ARDA, AYŞE]
pipe.count(); // IllegalStateException- Lazy: intermediate operations only record a recipe; elements are processed when the terminal operation is called.
- Elements pass through the pipeline one at a time: the first goes through
filterandmap, then the second comes. findFirstandlimitstop once they have the result; the remaining elements are never processed.- A stream is single-use: reusing it after a terminal operation throws
IllegalStateException; get a new stream from the source if needed.
The Stream API · Step-by-step code trace
A Lazy Stream Pipeline, Step by Step
List<String> names = Arrays.asList("Arda", "Ece", "Ayşe", "Can");
Stream<String> pipe = names.stream()
.filter(s -> { System.out.println("filter " + s);
return s.startsWith("A"); })
.map(s -> { System.out.println("map " + s);
return s.toUpperCase(); });
System.out.println("pipe ready");
List<String> result = pipe.collect(Collectors.toList());
System.out.println(result);The pipeline is built: filter and map are only recorded. No lambda has run; the output is empty.
This line is printed before any processing: intermediate operations are lazy.
collect runs the pipeline. The first element, Arda, enters filter: it starts with "A" → it passes.
The same element goes straight on to map, and ARDA is added to the result. Only now is it the second element’s turn.
Ece fails the condition: it is dropped and never reaches map.
Ayşe passes the filter.
map converts to upper case: AYŞE is added to the result.
Can is dropped. The source has no elements left.
collect returns the list. filter ran 4 times, map only twice.
The result is printed. The order of the output shows that elements pass through the pipeline one at a time.
The Stream API
reduce, Collectors and Primitive Streams
List<String> fruits = Arrays.asList(
"pear", "kiwi", "fig", "plum", "lemon");
int total = Arrays.asList(4, 8, 15, 16, 23)
.stream().reduce(0, Integer::sum);
Map<Integer, List<String>> byLen = fruits
.stream().collect(
Collectors.groupingBy(String::length));
String all = fruits.stream()
.collect(Collectors.joining(", "));
int t = IntStream.rangeClosed(1, 100).sum();
Optional<String> z = fruits.stream()
.filter(m -> m.startsWith("z")).findFirst();
System.out.println(z.orElse("none"));total = 66
byLen = {3=[fig],
4=[pear, kiwi, plum],
5=[lemon]}
all = pear, kiwi, fig,
plum, lemon
t = 5050
nonereduce: 0 + 4 + 8 + 15 + 16 + 23.groupingBygroups,joiningconcatenates.IntStream: a stream of numbers without boxing;sumandaveragebuilt in.Optional: there may be no result;orElse,ifPresent.
The Stream API
Side Effects and Parallel Streams
List<Integer> list = new ArrayList<>(); IntStream.range(0, 10000).parallel() .forEach(list::add); // WRONG: shared list List<Integer> safe = IntStream.range(0, 10000).parallel() .boxed() .collect(Collectors.toList()); // RIGHT: 10000 items
ArrayIndexOutOfBoundsException or fewer than 10000 items
- Lambdas should not modify outside variables; build the result with
map,collect,reduce. parallel()/parallelStream()splits the work across the commonForkJoinPoolthreads.ArrayListis not thread-safe, so the first pipeline breaks.- A parallel stream is not always faster: small data, cheap or I/O-bound work and order-dependent operations (
sorted,findFirst) can slow it; measure first.
peek; filling an outside collection with forEach; assuming a parallel stream is automatically faster.Choosing
Which Collection to Choose?
| Need | Choice | Why |
|---|---|---|
| Ordered list, indexed access | ArrayList | fast get(i); the default list |
| Frequent add/remove at the ends, queue, stack | ArrayDeque | O(1) at both ends; faster than Stack and LinkedList |
| Repeatedly taking the highest-priority element | PriorityQueue | poll gives the smallest (or highest-priority by the comparator) |
| Unique elements, fast “contains?” | HashSet | contains O(1) average |
| Unique + insertion order | LinkedHashSet | order preserved |
| Unique + sorted, range queries | TreeSet | first, headSet, subSet |
| Fast lookup from key to value | HashMap | get O(1) average; the default map |
| Sorted keys | TreeMap | firstKey, headMap, subMap |
With variables declared by interface type (List, Set, Map, Queue, Deque), only the new line changes when your needs change.
Choosing
Unmodifiable Collections
Factory methods (Java 9+)
List<String> r = List.of("red", "green");
Set<Integer> primes = Set.of(2, 3, 5);
Map<String, Integer> score =
Map.of("Ali", 90, "Banu", 85);
System.out.println(r);
System.out.println(score.get("Banu"));
r.add("blue");[red, green] 85
Exception in thread "main" java.lang.UnsupportedOperationException
add, remove and put throw. null elements are rejected; Set.of(1, 1) → IllegalArgumentException.
Read-only view (Java 1.2+)
List<String> list = new ArrayList<>();
list.add("a");
List<String> readOnly =
Collections.unmodifiableList(list);
list.add("b");
System.out.println(readOnly);
readOnly.add("c");[a, b]
Exception in thread "main" java.lang.UnsupportedOperationException
readOnly is a view: it cannot be modified itself, but it changes when the underlying list changes. Independent copy: List.copyOf(list) (Java 10+). Good for constant lists and hash keys.
Summary
Summary
| Class | Interface | Order | Duplicates | Underlying structure |
|---|---|---|---|---|
ArrayList | List | insertion | yes | dynamic array |
LinkedList | List, Deque | insertion | yes | doubly linked list |
Vector / Stack | List | insertion / LIFO | yes | synchronized array (legacy) |
ArrayDeque | Deque | FIFO or LIFO | yes | circular array |
PriorityQueue | Queue | removal by priority | yes | binary heap |
HashSet | Set | no guarantee | no | hash table |
LinkedHashSet | Set | insertion | no | hash + linked list |
TreeSet | NavigableSet | sorted | no | red-black tree |
HashMap | Map | no guarantee | key: no | hash table |
LinkedHashMap | Map | insertion | key: no | hash + linked list |
TreeMap | NavigableMap | sorted keys | key: no | red-black tree |
Iteration: for-each or Iterator (for removal). Algorithms: Collections.sort, shuffle, binarySearch, copy, fill, reverse, swap. Streams: filter, map, sorted (intermediate, lazy) and collect, reduce, count (terminal).
Practice
Common Mistakes (1/4)
Primitive type in a generic
List<int> grades = new ArrayList<>();
error: unexpected type
List<int> grades = new ArrayList<>();
^
required: reference
found: intCollections hold objects: the right type is List<Integer>. int values are autoboxed.
Adding an element of the wrong type
List<String> names = new ArrayList<>();
names.add(42);error: incompatible types: int cannot be converted to String
names.add(42);
^The generic type is checked at compile time. To store a number as a string, add String.valueOf(42).
Practice
Common Mistakes (2/4)
Confusing remove(int) and remove(Object)
List<Integer> list = new ArrayList<>(); Collections.addAll(list, 10, 20, 30); list.remove(1); // index 1 System.out.println(list); list.remove(Integer.valueOf(10)); // value 10 System.out.println(list);
[10, 30] [30]
On a List<Integer>, remove(1) removes index 1. To remove a value, pass Integer.valueOf(…).
Comparing Integers with ==
List<Integer> a = new ArrayList<>();
Collections.addAll(a, 1000, 1000);
System.out.println(a.get(0) == a.get(1));
System.out.println(a.get(0).equals(a.get(1)));false true
== compares references (it may happen to work between −128 and 127 because of caching). Compare values with equals.
Practice
Common Mistakes (3/4)
Adding to an Arrays.asList list
List<Integer> fixed = Arrays.asList(1, 2, 3); fixed.add(4);
Exception in thread "main" java.lang.UnsupportedOperationException
Arrays.asList returns a fixed-size list (set works, add/remove do not). Fix: new ArrayList<>(Arrays.asList(…)).
Iterating a Map directly with for-each
Map<String, Integer> m = new HashMap<>(); for (String s : m) { System.out.println(s); }
error: for-each not applicable to expression type
for (String s : m) {
^
required: array or java.lang.Iterable
found: Map<String,Integer>Map is not Iterable: iterate over keySet(), values() or entrySet().
Practice
Common Mistakes (4/4)
An index that does not exist
List<String> l = new ArrayList<>();
Collections.addAll(l, "a", "b", "c");
System.out.println(l.get(3));Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
Valid indices are 0 … size() − 1. On an empty queue remove() also throws NoSuchElementException; poll() returns null.
Sorting Turkish names
List<String> names = new ArrayList<>();
Collections.addAll(names,
"Zeynep", "Çağla", "Can", "Ömer");
Collections.sort(names);
System.out.println(names);
Locale tr = Locale.forLanguageTag("tr-TR");
Collections.sort(names, Collator.getInstance(tr));
System.out.println(names);[Can, Zeynep, Çağla, Ömer] [Can, Çağla, Ömer, Zeynep]
String sorts by character code: Ç, Ö, Ş, Ü, İ come after “Z”. A Collator (java.text) gives Turkish alphabetical order.
Practice
Practice Problems (1)
public class Fibonacci { public static int fibonacci(int num) { List<Integer> list = new ArrayList<>(); list.add(0); list.add(1); for (int i = 2; i < num + 1; i++) { list.add(list.get(i - 2) + list.get(i - 1)); } return list.get(num); } public static void main(String[] args) { int result = fibonacci(10); System.out.println(result); } }
- What does the program print?
- How many elements does the list hold when
fibonacci(10)returns? What are the last three? - How many times does the loop run for
fibonacci(1)? - Is a list really needed for this problem?
Show answers
- 55
- 11 elements (indices 0…10):
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; the last three are 21, 34, 55. - 0 times: for
i = 2,2 < 2is false;list.get(1)= 1 is returned. - No: two variables holding the last two values are enough (O(1) memory). A list helps when you need to keep the whole sequence.
Practice
Practice Problems (2)
public class Dedup { static List<String> dedup(List<String> input) { Set<String> seen = new LinkedHashSet<>(input); return new ArrayList<>(seen); } public static void main(String[] args) { List<String> l = Arrays.asList("b", "a", "b", "c", "a"); System.out.println(dedup(l)); } }
- What does the program print?
- What would change with a
HashSetorTreeSetinstead of theLinkedHashSet?
Show answers
- [b, a, c]: duplicates are dropped and the order of first appearance is kept.
HashSet: no order guarantee.TreeSet: alphabetical,[a, b, c].
Practice
Practice Problems (3)
static boolean isBalanced(String expr) { Deque<Character> stack = new ArrayDeque<>(); for (char c : expr.toCharArray()) { if (c == '(' || c == '[') { stack.push(c); } else if (c == ')' || c == ']') { if (stack.isEmpty()) return false; char open = stack.pop(); if (c == ')' && open != '(') return false; if (c == ']' && open != '[') return false; } } return stack.isEmpty(); }
Balanced brackets: every opening bracket must close with the right type, in the right order.
- What do
isBalanced("(a[b]c)"),isBalanced("(a[b)c]")andisBalanced("((")return? - Why use a stack?
Show answers
- true, false, false. In
(a[b)c], when)arrives the top is[; after((the stack is not empty. - The last bracket opened must be closed first: that is exactly LIFO behavior.
Practice
Practice Problems (4)
Deque<Integer> d = new ArrayDeque<>();
d.offerLast(1);
d.offerFirst(2);
d.offerLast(3);
d.push(4);
System.out.println(d);
System.out.println(d.pollLast() + d.pop());
System.out.println(d);Map<String, Integer> m = new TreeMap<>(); m.put("b", 1); m.put("a", 2); m.put("b", 3); Set<Integer> s = new TreeSet<>(m.values()); s.add(2); System.out.println(m + " " + s + " " + m.size());
What do the two fragments print? (push = offerFirst, pop = removeFirst.)
Show answers
[4, 2, 1, 3]: 1 →[1], 2 at the front →[2, 1], 3 at the end →[2, 1, 3],push(4)at the front →[4, 2, 1, 3].7:pollLast()gives 3 andpop()gives 4; theIntegers are added (3 + 4); then[2, 1]is left.{a=2, b=3} [2, 3] 2: the secondputsets"b"to 3; the values are {2, 3};s.add(2)is a duplicate and is not added; the size is 2.
Practice
Exercises (1)
- Which collection? (a) fast lookup of a student by number, (b) listing distinct words alphabetically, (c) print jobs, (d) a browser’s “back” button, (e) calling emergency patients by urgency.
- Using a
HashMap, write a methodmostFrequentthat returns the most frequent word in aString[].
Show answers
1. (a) HashMap<Integer, Student> (b) TreeSet<String> (c) ArrayDeque or LinkedList as a Queue (d) ArrayDeque as a stack (e) PriorityQueue + Comparator.
2. The solution alongside returns water for water, tea, water, coffee, water, tea.
static String mostFrequent(String[] words) { Map<String, Integer> counter = new HashMap<>(); for (String k : words) { counter.put(k, counter.getOrDefault(k, 0) + 1); } String best = null; int maxCount = 0; for (Map.Entry<String, Integer> g : counter.entrySet()) { if (g.getValue() > maxCount) { maxCount = g.getValue(); best = g.getKey(); } } return best; }
Practice
Exercises (2)
- Write the lottery draw without
shuffle, usingRandomand aTreeSet: 6 distinct numbers from 1–49, printed in order.
Show answers
Random r = new Random(); Set<Integer> drawn = new TreeSet<>(); while (drawn.size() < 6) { drawn.add(r.nextInt(49) + 1); // 1 … 49 } System.out.println(drawn);
[21, 27, 34, 43, 44, 45]
Sample output; it differs on every run. The set itself prevents repeats: if the same number comes up, add does not add it and the loop continues. TreeSet keeps the numbers sorted.
Practice
Exercises (3)
- Build a
Map<String, List<Integer>>holding each student’s list of grades; print the averages for Ali: 80, 90 and Banu: 70.
Show answers
Map<String, List<Integer>> grades = new TreeMap<>(); grades.put("Ali", new ArrayList<>()); grades.get("Ali").add(80); grades.get("Ali").add(90); grades.put("Banu", new ArrayList<>(Arrays.asList(70))); for (Map.Entry<String, List<Integer>> g : grades.entrySet()) { int total = 0; for (int n : g.getValue()) { total += n; } System.out.println(g.getKey() + " avg: " + total / g.getValue().size()); }
Ali avg: 85 Banu avg: 70
Since the value is a list, grades.get("Ali").add(80) adds to that list. The average uses integer division (170 / 2 = 85).
Summary
References
- Oracle, The Java Tutorials: Collections (Interfaces, Implementations, Algorithms) and Generics.
- Oracle, Java SE 21 API Documentation: package
java.util(Collection,List,Map,Collections…). - J. Gosling et al., The Java Language Specification, Java SE 21 Edition (4.5 Parameterized Types, 5.1.7 Boxing Conversion, 14.14.2 Enhanced for).
- P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapter 16: Generic Collections).
- K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly (Chapter 11: Data Structures).
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson (Chapter 9: Collections).
- M. Naftalin and P. Wadler, Java Generics and Collections, O'Reilly.
- J. Bloch, Effective Java, 3rd ed., Addison-Wesley (Item 11: override hashCode when you override equals; Item 64: refer to objects by their interfaces).