Java Iterator pattern and Comparable for sorting
Iterator interface, hasNext, next, Iterable, Comparable, compareTo, Comparator, Collections.sort, custom sort order, natural ordering
Iterating and Sorting Collections
Java collections support two sorting mechanisms: natural order via Comparable embedded in the class, and custom order via an external Comparator.
Iterator — Safe Removal During Traversal
List items = new ArrayList<>(List.of("c", "a", "b"));
Iterator it = items.iterator();
while (it.hasNext()) {
String val = it.next();
if (val.equals("a")) it.remove(); // safe — ConcurrentModificationException avoided
}
System.out.println(items); // [c, b]
Comparable — Natural Order
public class Employee implements Comparable {
String name;
double salary;
public Employee(String name, double salary) {
this.name = name; this.salary = salary;
}
@Override
public int compareTo(Employee other) {
return Double.compare(this.salary, other.salary); // ascending
}
}
Comparator — On-the-fly Custom Order
List staff = new ArrayList<>();
staff.add(new Employee("Alice", 80000));
staff.add(new Employee("Bob", 65000));
Collections.sort(staff); // natural: salary ascending
staff.sort(Comparator.comparing(e -> e.name)); // alphabetical
staff.sort(Comparator.comparingDouble((Employee e) -> e.salary).reversed());
compareTo returns negative if this is less, zero if equal, positive if greater. Comparator lets you sort without modifying the class — essential for third-party types or multiple independent sort orders in the same program.
Never modify a collection directly while iterating with a for-each loop — it throws ConcurrentModificationException. Use an Iterator with remove() for safe structural modifications during traversal, or collect items to remove and delete them after the loop.
