Introduction to Iterators

Input/Output and Streams in Java

Alex Liu

Software Development Engineer

Working with collections

  • Example HashSet for the rest of the video
import java.util.HashSet;

public class SampleHashSetData { public static void main(String[] args) { HashSet<String> fruits = new HashSet<>();
fruits.add("Apple"); fruits.add("Banana");
} }
{Apple, Banana}
Input/Output and Streams in Java

Use For-Each loop

  • For-Each loop
    • Format: for (type x: collection){}
    • Automatically processes each element
    • Works for Multiple Collections: List, Set, Map and more
  • Example: use sample set fruits: [Apple, Banana].
for (String x : fruits) {
    System.out.println(x);
}
Apple
Banana
Input/Output and Streams in Java

Traversing a collection with Iterator

  • Use Iterator<>: Supports List, Set, Queue and more
  • Import Iterator class
import java.util.Iterator;

// Create `Iterator` object named `it` for sample set `fruits` Iterator<String> it = fruits.iterator(); // Use `.hasNext()` method checks if more elements exist while (it.hasNext()) { // User `.next()` retrieves the element System.out.print(it.next());}
Apple Banana
Input/Output and Streams in Java

Removing elements with Iterator

  • Use .remove() to remove element with Iterator

$$

Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
    String fruit = it.next();
    if (fruit.startsWith("A")) {
        // Remove element if element startsWith `A`
        it.remove();
        }
}
// fruits now contains only "Banana"
Input/Output and Streams in Java

Removing elements with Iterator(Continued)

  • Before Removal:

    System.out.println(fruits);
    
    [Apple, Banana]
    
  • After Removal:

    System.out.println(fruits);
    
    [Banana]
    
  • Ensures safe deletion and prevent ConcurrentModificationException

Icon representing safe deletion

Input/Output and Streams in Java

Summary

  • For-Each loop
    • Support
      • List(ArrayList,LinkedList)
      • Set(HashSet,TreeSet,LinkedHashSet)
      • Queue(PriorityQueue)
      • Stack(Stack)
    • Not Support
      • Map
      • Element Removal
  • Iterator
    • Support
      • List(ArrayList,LinkedList)
      • Set(HashSet,TreeSet,LinkedHashSet)
      • Queue(PriorityQueue)
      • Stack(Stack)
      • Map (Must use keySet().iterator, values().iterator or entrySet().iterator)
      • Element Removal
Input/Output and Streams in Java

Let's practice!

Input/Output and Streams in Java

Preparing Video For Download...