Lesson 31 of 36Article16 min
Iterator & Algorithms
Iterator has hasNext() and next() to visit elements safely during removal.
Iterator — walk a collection
Iterator has hasNext() and next() to visit elements safely during removal.
Enhanced for-loop uses iterator internally. Use explicit iterator when removing while looping.
Real-life example: Iterator is a ticket checker at cinema — hasNext "any seats left?", next "here is seat 7".
Iterator example
import java.util.*;
List<String> fruits = new ArrayList<>(List.of("Apple", "Banana", "Cherry"));
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}Algorithms — Collections utility methods
Collections.max, min, frequency, reverse, shuffle, binarySearch work on lists.
Arrays class has similar helpers for arrays: Arrays.sort, Arrays.toString.
Real-life example: Algorithms are quick tools in a Swiss knife — sort, find max, count duplicates without rewriting loops.
Collections algorithms
import java.util.*;
List<Integer> list = new ArrayList<>(List.of(5, 2, 8, 2));
System.out.println(Collections.max(list)); // 8
System.out.println(Collections.frequency(list, 2)); // 2
Collections.sort(list);
System.out.println(list); // [2, 2, 5, 8]