Working with Iterators and Comparators
1. Using Iterator Interface
| Method | Detail |
|---|---|
hasNext() | Check next element |
next() | Return next, advance |
remove() | Remove last returned (optional op) |
forEachRemaining(c) | Java 8+ |
Warning: Modifying collection outside iterator throws
ConcurrentModificationException.2. Using ListIterator
| Extra Methods | Use |
|---|---|
hasPrevious / previous | Bidirectional |
add(e) | Insert at cursor |
set(e) | Replace last returned |
nextIndex / previousIndex | Cursor position |
3. Using Enhanced for Loop
| Aspect | Detail |
|---|---|
| Syntax | for (T x : iterable) { ... } |
| Works for | Arrays + Iterable |
| Limitations | No index, cannot remove |
4. Using forEach() Method
Example: forEach
list.forEach(System.out::println);
map.forEach((k, v) -> System.out.println(k + "=" + v));
| Source | Signature |
|---|---|
Iterable | forEach(Consumer) |
Map | forEach(BiConsumer) |
Stream | forEach (no order) / forEachOrdered |
5. Implementing Comparable Interface
Example: Comparable
public class Version implements Comparable<Version> {
int major, minor, patch;
@Override public int compareTo(Version o) {
if (major != o.major) return Integer.compare(major, o.major);
if (minor != o.minor) return Integer.compare(minor, o.minor);
return Integer.compare(patch, o.patch);
}
}
| Contract | Detail |
|---|---|
| Sign | <0 / 0 / >0 |
| Antisymmetric | sgn(a.compareTo(b)) == -sgn(b.compareTo(a)) |
| Transitive | a<b, b<c → a<c |
| Consistency with equals | Strongly recommended |
6. Implementing Comparator Interface
| Approach | Detail |
|---|---|
| Class | class ByLen implements Comparator<String> |
| Lambda | (a,b) -> a.length() - b.length() |
| Factory | Comparator.comparingInt(String::length) |
7. Creating Comparator with Lambda
Example: Lambda comparator
Comparator<String> byLength = (a, b) -> Integer.compare(a.length(), b.length());
Comparator<User> byAge = Comparator.comparingInt(User::age);
| Tip | Detail |
|---|---|
Avoid a - b for ints | Overflow risk; use Integer.compare |
| Null handling | Use Comparator.nullsFirst/nullsLast |
8. Chaining Comparators
| Method | Use |
|---|---|
.thenComparing(other) | Tiebreaker |
.thenComparingInt(fn) | Primitive optimization |
9. Reversing Comparators
| Method | Behavior |
|---|---|
cmp.reversed() | Reverses order |
Comparator.reverseOrder() | Natural reverse |
10. Using Comparator Factory Methods
| Factory | Description |
|---|---|
naturalOrder() | Uses Comparable |
comparing(keyFn) | By extracted key |
comparingInt/Long/Double | Avoid boxing |
nullsFirst(cmp) / nullsLast(cmp) | Null-safe |
11. Understanding Natural Ordering vs Custom Ordering
| Aspect | Comparable | Comparator |
|---|---|---|
| Defined in | Class itself | External |
| One per class | Yes | Many possible |
| Method | compareTo | compare |
| When to use | Inherent ordering exists | Multiple/contextual orderings |