Chapter 5: Collections

Object Oriented Programming with Java
The collections frameworkGeneric typesArrayList and LinkedListVector and Stack Queue and PriorityQueueDeque and ArrayDequeSet: HashSet, TreeSetMap: HashMap, TreeMap IteratorSorting and searchingShuffling and compositionThe Stream API
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Framework

Explain the interfaces, implementations and algorithms of the collections framework and its interface/class hierarchy.

Generic types

Write type-safe code with generic types such as List<String>; use wrapper classes and autoboxing.

Lists

Use ArrayList, LinkedList, Vector and Stack; explain their performance differences.

Queues

Build FIFO, priority and LIFO behavior with Queue, PriorityQueue and ArrayDeque.

Sets and maps

Choose correctly among HashSet, TreeSet, HashMap, TreeMap and their linked versions.

Iteration, algorithms, streams

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, remove and contains come 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
Analogy: an array is a bus with a fixed number of seats; an ArrayList is a bus that grows as passengers board.

The Collections Framework

Kinds of Collections

List

Ordered, indexed elements; duplicates allowed. ArrayList, LinkedList

AliCanAliEce
Set

Unique elements only; the same element is not added twice. HashSet, TreeSet

AliCanEce
Map

Key → value pairs; each key appears once. HashMap, TreeMap

Ali → 85Can → 72
Queue

Elements waiting to be processed; usually first in, first out (FIFO). LinkedList, PriorityQueue

head: AliCanEce: tail

The Collections Framework

Core Operations and Design Goals

Core operations

Add, remove, update and search; easy iteration with a for-each loop.

Ease of use

A simple, clear API: code is easier to read and maintain.

Performance

Memory-efficient structures optimized for data volume and access patterns.

Type safety

Generic types (List<String>) catch elements of the wrong type at compile time.

Rich hierarchy

A family of classes for different needs, working smoothly with the rest of the standard library.

Ready-made algorithms

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

«interface»Iterable«interface»Collection«interface»List«interface»Queue«interface»Set«interface»Mapseparate hierarchy(not a Collection)
  • Iterable: anything you can loop over with for-each (the iterator() method).
  • Collection: methods common to all collections (add, remove, size…).
  • List, Queue, Set: subinterfaces that extend Collection.
  • Map: a key–value structure. It is part of the framework but does not extend Collection.

The arrows follow UML: a hollow triangle points to the extended (parent) interface.

The Collections Framework

Collection Classes

«interface»Collection«interface»List«interface»Queue«interface»SetArrayListVectorStackLinkedListPriorityQueue«interface»DequeArrayDequeHashSetLinkedHashSet«interface»SortedSet«interface»NavigableSetTreeSetinterfaceclassextendsimplements

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

Interface

Defines how a data structure should behave (what it does). Example: List represents an ordered list.

Implementation

The actual class that implements the interface (how it does it). Example: ArrayList implements List with a dynamic array.

Algorithm

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]
Modular design: each component has a clear role and responsibility. Flexibility: different implementations and algorithms work together through the same interface.

The Collections Framework

Programming to an Interface

  • An interface defines a behavior; classes implement it with their own methods.
  • Different kinds of storage: ArrayList is a dynamic array, LinkedList a doubly linked list, HashMap a 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 get needs 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 typeWrapper class
intInteger
doubleDouble
charCharacter
booleanBoolean
longLong

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 ArrayList keeps elements in insertion order; add appends to the end.
  • Phone book: a HashMap maps a key (the name) to a value (the number).
  • Add with put(key, value); look up the value with get(key).
  • Printing a list with println shows its elements inside [ … ].

The Collections Framework

Methods of the Collection Interface

MethodPurposeReturns
add(E e)adds the elementboolean: true if added
remove(Object o)removes the elementboolean
size()gives the number of elementsint
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 arrayObject[]
iterator()gives an iterator for traversalIterator<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 indexed get).
  • 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; prefer ArrayList.
MethodPurpose
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 AbstractList and implements the List interface.
  • 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
O(1): time independent of the number of elements (constant). O(n): time proportional to the number of elements n.

Lists

How Does an ArrayList Grow?

internal array (elements)A0B1C23size = 3, capacity = 4

Take a list created with new ArrayList<>(4), initial capacity 4: inside is a 4-cell array, 3 cells in use.

internal array (elements)A0B1C2D3size = 4, capacity = 4 (full)

add("D"): there is a free cell; D goes straight to the end. Nothing moves: O(1).

internal array (elements)A0B1C2D3new array: capacity 4 + 4/2 = 6A0B1C2D3454 elements copied

add("E"): the array is full! A larger array is allocated and the 4 old elements are copied one by one: O(n).

internal array (elements)A0B1C2D3old array: no longer usednew array: capacity 4 + 4/2 = 6A0B1C2D3E45size = 5, capacity = 6

E is written at index 4 of the new array. The old array is left to the garbage collector.

The default capacity is 10; each growth makes it about 1.5 times larger. Since copying happens only now and then, appending is O(1) on average (amortized). Capacity is not size(): size() is the number of occupied cells.

Lists · Step-by-step code trace

ArrayList Methods: Trace

namessize = 0empty list

An empty ArrayList is created: size() is 0.

namessize = 1Ali0

add appends the element: Ali is at index 0.

namessize = 5Ali0Banu1Cem2Deniz3Ece4

Four more elements are appended; indices 0…4.

namessize = 5Ali0Banu1Cem2Deniz3Ece4

The list is printed: elements in insertion order.

namessize = 5Ali0Banu1Cem2Can3Ece4

set(3, "Can"): Can replaces Deniz at index 3. The size does not change.

namessize = 4Ali0Banu1Cem2Can3

remove(4): Ece at index 4 is removed. It is the last element, so nothing shifts.

namessize = 5Ali0Banu1Fatma2Cem3Can4

add(2, "Fatma"): Cem and Can each shift one place right; Fatma goes in at index 2.

namessize = 5Ali0Banu1Fatma2Cem3Can4

indexOf("Banu") searches from the start and returns the first position: 1.

namessize = 5Ali0Banu1Fatma2Cem3Can4

contains("Ece"): Ece was removed earlier, so the result is false.

namessize = 5Ali0Banu1Fatma2Cem3Can4

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);
1002013024034

Start: [10, 20, 30, 40]. Now add(1, 15) runs.

10012023034043 elements right

First the elements after index 1 shift one place right (starting from the end); cell 1 becomes free.

100151202303404[10, 15, 20, 30, 40]

15 goes into the free cell. In a list of n elements the worst case is n shifts: O(n).

1001512023034044 elements left

remove(0): 10 is removed and the 4 elements behind it shift one place left.

150201302403[15, 20, 30, 40]

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 the List and Deque interfaces.
  • 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).
CherryprevnextAppleprevnextPearprevnextBananaprevnextnullnullfirstlast

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]
MethodPurpose
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

first = nulllast = null

Empty list: the first and last references are null. There is no such thing as capacity.

Applefirstlast

A node is created for Apple; the single node is both first and last.

ApplePearfirstlast

Pear is linked at the end: Apple.next → Pear, Pear.prev → Apple; last is updated.

CherryApplePearfirstlast

addFirst: Cherry goes to the front; only a few references change and nothing shifts: O(1).

CherryApplePearBananafirstlast

addLast: Banana goes to the end, again O(1).

CherryApplePearBananafirstlast

println walks the list from front to back along the next links.

CherryApplePearBananafirstlast

getFirst(): the node first points to, Cherry.

CherryApplePearBananafirstlast

getLast(): the node last points to, Banana. For an element in the middle (get(i)) you walk node by node.

CherryApplePearBananafirstlastunlinked

removeFirst(): first moves to Apple and Apple.prev becomes null; the Cherry node drops out of the list.

ApplePearBananafirstlast

[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?

OperationArrayListLinkedList
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 frontO(n): every element shiftsO(1)
Insert / remove in the middleO(n): shiftingO(n): find the position + O(1) relinking
Memory uselow: just the arrayhigh: 2 extra references per node
In most cases ArrayList is the right choice. If insertions and removals are frequent, especially at the ends of the list, prefer LinkedList (or ArrayDeque for a queue or stack).

Lists

The Vector Class

  • A growable dynamic array that implements the List interface.
  • 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 elementgives the element at iremoves the elementnumber of elementscurrent 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 Vector class.
  • Uses: undo, parsing text and expressions (bracket matching), depth-first search, the method call stack.
  • Modern code should use ArrayDeque (or LinkedList), which implements the Deque interface.

Analogy: a pile of plates; you always take from and put on the top.

MethodPurpose
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
CBAtopbasepush(C)pop() → C

Lists · Step-by-step code trace

Stack: Trace

emptybase

An empty stack is created.

Atop →base

push("A"): A goes on top.

ABtop →base

push("B"): B on top of A.

ABCtop →base

push("C"): now C is on top.

ABCtop →base

println prints the elements bottom to top: [A, B, C].

ABCtop →base

peek() returns the top element (C) without removing it.

ABCtop →base

pop() removes and returns C: last in, first out.

A2B1← topbase

search("A") counts positions from the top, starting at 1: B is 1, A is 2.

ABtop →base

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, poll and peek.
  • Implementations: LinkedList (doubly linked list), PriorityQueue (by priority, not FIFO), ArrayDeque (dynamic array).
  • Uses: print queues, task queues, breadth-first search.
AliBanuCemheadtailpoll()offer(e)

Analogy: a supermarket checkout. You join at the back; the person at the front pays.

OperationThrows exceptionReturns 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

outempty queue← in

The variable has type Queue; the object is a LinkedList.

outAlihead = tail← in

offer("Ali"): Ali joins the queue; he is both head and tail.

outAliBanuheadtail← in

Banu joins at the tail.

outAliBanuCemheadtail← in

Cem joins at the tail.

outAliBanuCemheadtail← in

The queue is printed head to tail.

outAliBanuCemheadtail← in

peek() returns the head without removing it.

outBanuCemheadtailAli← in

poll() removes and returns the head: Ali, first in, is first out.

outCemhead = tailBanu← in

Next, Banu leaves.

outCemhead = tail← in

size(): 1 element left in the queue.

outempty queueCem← in

Cem leaves too; the queue is empty.

outempty queue← in

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 a Comparator must be supplied.
  • Internally a binary heap: add/poll O(log n), peek O(1); grows dynamically.
  • Uses: task scheduling, emergency-room triage, shortest-path algorithms.
MethodPurpose
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
10204030← peek / poll100201402303array

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 
10[0]20[1]40[2]30[3]internal array:100201402303

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

(empty)array0123

Inside, an empty array: a binary heap. Rule: every parent is less than or equal to its children.

30array300123

30 goes to the root (index 0).

1030array10030123

10 is appended (index 1); it is smaller than its parent 30, so it moves up and they swap. The root is now 10.

103040array1003014023

40 goes to index 2; it is larger than its parent 10 and stays.

10204030array100201402303

20 goes to index 3; smaller than its parent 30 → swap; larger than 10 → stop.

10204030array100201402303

peek(): the root, i.e. the smallest element: 10. The queue is unchanged; O(1).

10204030array100201402303

println prints the internal array as is: [10, 20, 40, 30] is not sorted.

203040array2003014023out: 10

poll(): the root 10 leaves; the last element, 30, moves to the root and swaps with its smaller child 20, sinking down.

3040array30040123out: 20

20 leaves; 40 moves to the root and swaps with 30.

40array400123out: 30

30 leaves; only 40 is left.

(empty)array0123out: 40

40 leaves; the queue is empty and the loop ends. They came out sorted: 10 20 30 40.

(empty)array0123

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) and Stack (LIFO) behavior.
  • Implementations: LinkedList (doubly linked list) and ArrayDeque (dynamic array).
1510head (first)tail (last)addFirst / offerFirstremoveFirst / pollFirstaddLast / offerLastremoveLast / pollLast
HeadPurposeTailPurpose
addFirst(e)adds to the frontaddLast(e)appends
removeFirst()removes and returns the headremoveLast()removes and returns the tail
getFirst()returns the headgetLast()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 LinkedList and Stack; the recommended class for stacks and queues.
  • Does not accept null elements.
MethodPurpose
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.

100123451657head ▲▲ tailwraps from end to start

Queues · Step-by-step code trace

ArrayDeque: Trace

empty

An empty ArrayDeque.

5head = tail

addFirst(5): 5 goes to the front (the only element).

510headtail

addLast(10): 10 goes to the end.

1510headtail

addFirst(1): 1 goes to the front; 5 and 10 stay in place.

1510headtail

Printed from head to tail.

510headtail1

pollFirst() removes the 1 at the head; it is unboxed into an int.

5head = tail10

pollLast() removes the 10 at the tail.

5head = tail

Both values are printed.

5head = tail

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: add does not add an existing element and returns false.
  • 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 a Comparator).
MethodPurpose
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 AbstractSet and implements Set.
  • 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.
0123456789101112131415buckets: 0 … 15

Inside is a table of 16 buckets (it grows as it fills).

012salt3456789101112131415buckets: 0 … 15"salt".hashCode() = 3522646 → bucket 3

add("salt"): bucket 3 is computed from the hash, and salt goes there.

012salt3egg456789101112131415buckets: 0 … 15"egg".hashCode() = 100357 → bucket 4

add("egg"): bucket 4.

012salt3egg4567milk89101112131415buckets: 0 … 15"milk".hashCode() = 3351579 → bucket 8

add("milk"): bucket 8.

012salt3egg4567milk89101112131415buckets: 0 … 15"egg".hashCode() = 100357 → bucket 4already there → not added

The second add("egg"): bucket 4 already holds an element that is equals to it. It is not added; add returns false.

012salt3egg456coffee7milk89101112131415buckets: 0 … 15"coffee".hashCode() = -1355030580 → bucket 7

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]
MethodPurpose
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]
ClassIteration orderUnderlying structureadd / contains
HashSetno guarantee (bucket order)hash tableO(1) average
LinkedHashSetinsertion orderhash table + linked listO(1) average
TreeSetsorted (ascending)red-black treeO(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’s equals compares references) → size 2.
  • Point: equals and hashCode are 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

buckets0123456789101112131415

HashSet uses a 16-bucket hash table internally. Point’s equals and hashCode are computed from x and y.

buckets0123456789101112131415(1, 2)hash = 994 → bucket 2p

Objects.hash(1, 2) = 994. The bucket number is the last 4 bits of the hash: 994 → bucket 2.

buckets0123456789101112131415(1, 2)hash = 994 → bucket 2p

add(p): the object lands in bucket 2.

buckets0123456789101112131415(1, 2)hash = 994 → bucket 2p

contains(p): bucket 2 is checked again and equals is true → true.

buckets0123456789101112131415(5, 2)hash = 1118 → bucket 14p

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.

buckets0123456789101112131415(5, 2)hash = 1118 → bucket 14p

contains(p): bucket 14 is checked; it is empty → false. The object is in the set but cannot be found.

buckets0123456789101112131415(5, 2)hash = 1118 → bucket 14p(1, 2)

The new Point(1, 2) goes to bucket 2; the object there is now (5, 2), so equals is false → false.

buckets0123456789101112131415(5, 2)hash = 1118 → bucket 14p

add(p): bucket 14 looks empty, so the same object is added a second time.

buckets0123456789101112131415(5, 2)hash = 1118 → bucket 14p

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 supplied Comparator.
  • It offers subset and superset operations.
  • TreeSet: extends AbstractSet and implements NavigableSet (and therefore SortedSet).
  • Internally a red-black tree: insertion, removal and lookup are O(log n).
MethodPurpose
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, removeinsertion, removal
7050906080headSet(70)= [50, 60]smaller → leftlarger → right

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
AB12345A ∩ B
OperationMethod
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 a Comparator).

Analogy: a dictionary. You find the meaning (value) by the word (key); the same word does not appear twice.

«interface»MapHashMapHashtable«interface»SortedMapLinkedHashMap«interface»NavigableMapTreeMap

Maps

Map Methods

MethodPurpose
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/put are O(1) on average.
  • Extends AbstractMap and implements Map.
  • Unique keys: put with an existing key replaces the value.
  • Null: allows one null key and any number of null values.
  • 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 a Map.Entry, read with getKey() and getValue(). The most efficient way when you need both key and value.
  • A Map cannot be given directly to for-each: it is not Iterable.

Maps · Step-by-step code trace

Counting Words: Trace

keyvalueempty

The text and an empty TreeMap are set up. split(" ") breaks the text into words.

keyvalue"egg"1

"egg" is seen for the first time: put(k, 1).

keyvalue"coffee"1"egg"1

"coffee" is seen for the first time: put(k, 1).

keyvalue"coffee"1"egg"2

"egg" is already there: the old value 1 is read and 2 is stored.

keyvalue"coffee"1"egg"2"milk"1

"milk" is seen for the first time: put(k, 1).

keyvalue"coffee"2"egg"2"milk"1

"coffee" is already there: the old value 1 is read and 2 is stored.

keyvalue"coffee"2"egg"3"milk"1

"egg" is already there: the old value 2 is read and 3 is stored.

keyvalue"coffee"2"egg"3"milk"1

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, HashMap is 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: HashMap is not synchronized; every Hashtable method takes a lock.
  • Neither keys nor values may be null.
  • Locking makes it slower than modern alternatives; use HashMap in single-threaded code and ConcurrentHashMap in 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: extends AbstractMap and implements NavigableMap.
  • Keys are ordered by natural order or a supplied Comparator.
  • Internally a red-black tree: get/put O(log n).
MethodPurpose
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, removesame 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

HashMapLinkedHashMapTreeMapHashtable
Iteration orderno guaranteeinsertion ordersorted keysno guarantee
get / putO(1) averageO(1) averageO(log n)O(1) average, locked
null keyoneonenono
null valueyesyesyesno
Synchronizednononoyes (legacy)
When?the default choiceorder must be keptsorted keys, range querieslegacy code
The same logic applies to sets: 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() (or removeIf for bulk removal).
  • A for-each loop uses an Iterator behind the scenes.
  • For lists, ListIterator can also move backwards and supports add and set.
MethodPurpose
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).

385cursornext() → 3hasNext() → true

Iterators · Step-by-step code trace

Iterator: Trace

308152

The list is set up: [3, 8, 5].

308152cursor

iterator(): the cursor is placed before the first element.

308152cursor

hasNext() is true; next() returns 3 and advances the cursor.

308152cursor

The element is printed.

308152cursor

hasNext() is true; next() returns 8 and advances the cursor.

308152cursor

The element is printed.

308152cursor

hasNext() is true; next() returns 5 and advances the cursor.

308152cursor

The element is printed.

308152cursor

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?

s (internal array)6091122size = 3modCount = 0

The list has 3 elements; modCount (the structural modification counter) is 0.

s (internal array)6091122size = 3cursor = 0modCount = 0expected = 0=

for-each secretly calls s.iterator(): cursor = 0, and the iterator saves the current modCount: expectedModCount = 0.

s (internal array)6091122size = 3cursor = 0modCount = 0expected = 0=

hasNext(): cursor (0) ≠ size (3) → true.

s (internal array)6091122size = 3cursor = 1modCount = 0expected = 0=

next(): first the counters are compared (0 = 0); x = 6, cursor = 1.

s (internal array)6091122size = 3cursor = 1modCount = 0expected = 0=

6 is even.

s (internal array)901212size = 2cursor = 1modCount = 1expected = 0≠

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.

s (internal array)901212size = 2cursor = 1modCount = 1expected = 0≠

hasNext(): cursor (1) ≠ size (2) → true; the loop goes on.

s (internal array)901212size = 2cursor = 1modCount = 1expected = 0≠ConcurrentModificationException

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

  • Collection is an interface; Collections (with an s) is a utility class of ready-made static methods 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.
Sorting

sort, reverse, reverseOrder

Shuffling

shuffle

Searching

binarySearch, max, min, frequency

Composition

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]
MethodPurpose
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 writes compareTo.
  • Result: negative → this first; 0 → equal; positive → other first.
  • Integer.compare is 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

Linear search

Checks the elements one by one from start to end. No sorting required; good for small collections. O(n). Examples: indexOf, contains.

Binary search

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 search
3
-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.

If absent, the result is negative: −(insertion point) − 1; on an unsorted list it is undefined. For a million elements: linear search up to a million comparisons, binary at most 20.

Algorithms

Composition Algorithms

MethodPurpose
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 / minlargest / 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

namesAhmetAyşeCemtargetX0Y1Z2W3

Arrays.asList is a fixed-size list; target is a 4-element ArrayList.

namesAhmetAyşeCemtargetAhmet0Ayşe1Cem2W3

copy: the 3 elements are written to positions 0–2 of the target; W stays.

namesAhmetAyşeCemtargetW0Cem1Ayşe2Ahmet3

reverse: the order flips.

namesAhmetAyşeCemtargetAyşe0Cem1W2Ahmet3

swap(target, 0, 2): positions 0 and 2 trade places.

namesAhmetAyşeCemtargetJava0Java1Java2Java3

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.
sourcegrades.stream()intermediatefilter(n ≥ 50)intermediatemap(n + 5)intermediatesorted()terminalcollect(...)45 82 67 90 38 7582 67 90 7587 72 95 8072 80 87 95[72, 80, 87, 95]intermediate operations return a new stream; nothing is computed until the terminal operation is called
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);
Output
[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

IntermediatePurpose
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)
TerminalResult
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 / noneMatchboolean
min / maxOptional
An intermediate operation returns a new stream and the chain goes on; a terminal operation returns a non-stream result (or nothing) and runs the pipeline. A pipeline without a terminal operation does nothing.

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 filter and map, then the second comes.
  • findFirst and limit stop 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);
sourceArdaEceAyşeCanfiltermapresult

The pipeline is built: filter and map are only recorded. No lambda has run; the output is empty.

sourceArdaEceAyşeCanfiltermapresult

This line is printed before any processing: intermediate operations are lazy.

sourceArdaEceAyşeCanfilterArdamapresulttrue

collect runs the pipeline. The first element, Arda, enters filter: it starts with "A" → it passes.

sourceArdaEceAyşeCanfiltermapArdaresultARDA

The same element goes straight on to map, and ARDA is added to the result. Only now is it the second element’s turn.

sourceArdaEceAyşeCanfilterEcemapresultARDAfalse

Ece fails the condition: it is dropped and never reaches map.

sourceArdaEceAyşeCanfilterAyşemapresultARDAtrue

Ayşe passes the filter.

sourceArdaEceAyşeCanfiltermapAyşeresultARDAAYŞE

map converts to upper case: AYŞE is added to the result.

sourceArdaEceAyşeCanfilterCanmapresultARDAAYŞEfalse

Can is dropped. The source has no elements left.

sourceArdaEceAyşeCanfiltermapresultARDAAYŞE

collect returns the list. filter ran 4 times, map only twice.

sourceArdaEceAyşeCanfiltermapresultARDAAYŞE

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"));
Values
total = 66
byLen = {3=[fig],
  4=[pear, kiwi, plum],
  5=[lemon]}
all = pear, kiwi, fig,
  plum, lemon
t = 5050
none
  • reduce: 0 + 4 + 8 + 15 + 16 + 23.
  • groupingBy groups, joining concatenates.
  • IntStream: a stream of numbers without boxing; sum and average built 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
Result of the first pipeline (differs per run)
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 common ForkJoinPool threads. ArrayList is 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.
Common mistakes: reusing a stream; doing the real work inside peek; filling an outside collection with forEach; assuming a parallel stream is automatically faster.

Choosing

Which Collection to Choose?

NeedChoiceWhy
Ordered list, indexed accessArrayListfast get(i); the default list
Frequent add/remove at the ends, queue, stackArrayDequeO(1) at both ends; faster than Stack and LinkedList
Repeatedly taking the highest-priority elementPriorityQueuepoll gives the smallest (or highest-priority by the comparator)
Unique elements, fast “contains?”HashSetcontains O(1) average
Unique + insertion orderLinkedHashSetorder preserved
Unique + sorted, range queriesTreeSetfirst, headSet, subSet
Fast lookup from key to valueHashMapget O(1) average; the default map
Sorted keysTreeMapfirstKey, 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

ClassInterfaceOrderDuplicatesUnderlying structure
ArrayListListinsertionyesdynamic array
LinkedListList, Dequeinsertionyesdoubly linked list
Vector / StackListinsertion / LIFOyessynchronized array (legacy)
ArrayDequeDequeFIFO or LIFOyescircular array
PriorityQueueQueueremoval by priorityyesbinary heap
HashSetSetno guaranteenohash table
LinkedHashSetSetinsertionnohash + linked list
TreeSetNavigableSetsortednored-black tree
HashMapMapno guaranteekey: nohash table
LinkedHashMapMapinsertionkey: nohash + linked list
TreeMapNavigableMapsorted keyskey: nored-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:    int

Collections 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);
    }
}
  1. What does the program print?
  2. How many elements does the list hold when fibonacci(10) returns? What are the last three?
  3. How many times does the loop run for fibonacci(1)?
  4. Is a list really needed for this problem?
Show answers
  1. 55
  2. 11 elements (indices 0…10): [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; the last three are 21, 34, 55.
  3. 0 times: for i = 2, 2 < 2 is false; list.get(1) = 1 is returned.
  4. 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));
    }
}
  1. What does the program print?
  2. What would change with a HashSet or TreeSet instead of the LinkedHashSet?
Show answers
  1. [b, a, c]: duplicates are dropped and the order of first appearance is kept.
  2. 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.

  1. What do isBalanced("(a[b]c)"), isBalanced("(a[b)c]") and isBalanced("((") return?
  2. Why use a stack?
Show answers
  1. true, false, false. In (a[b)c], when ) arrives the top is [; after (( the stack is not empty.
  2. 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
  1. [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].
  2. 7: pollLast() gives 3 and pop() gives 4; the Integers are added (3 + 4); then [2, 1] is left.
  3. {a=2, b=3} [2, 3] 2: the second put sets "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)

  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.
  2. Using a HashMap, write a method mostFrequent that returns the most frequent word in a String[].
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)

  1. Write the lottery draw without shuffle, using Random and a TreeSet: 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)

  1. 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).

The End

Chapter 5: Collections
Previous: Chapter 4.5: Abstract Classes and Interfaces · Next: Chapter 6: Exceptions
1 / 1 Sercan KÜLCÜ. All rights reserved.