Úvod do iterátorů

Input/Output and Streams in Java

Alex Liu

Software Development Engineer

Práce s kolekcemi

  • Příklad HashSet pro zbytek videa
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

Použití smyčky For-Each

  • For-Each loop
    • Formát: for (type x: collection){}
    • Automaticky zpracuje každý prvek
    • Funguje pro více kolekcí: List, Set, Map a další
  • Příklad: použití sady fruits: [Apple, Banana].
for (String x : fruits) {
    System.out.println(x);
}
Apple
Banana
Input/Output and Streams in Java

Procházení kolekce pomocí iterátoru

  • Použití Iterator<>: podporuje List, Set, Queue a další
  • Import třídy Iterator
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

Odebírání prvků pomocí iterátoru

  • Použití .remove() k odebrání prvku pomocí 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

Odebírání prvků pomocí iterátoru (pokračování)

  • Před odebráním:

    System.out.println(fruits);
    
    [Apple, Banana]
    
  • Po odebrání:

    System.out.println(fruits);
    
    [Banana]
    
  • Zajišťuje bezpečné mazání a zabraňuje výjimce ConcurrentModificationException

Ikona znázorňující bezpečné mazání

Input/Output and Streams in Java

Shrnutí

  • For-Each smyčka
    • Podporuje
      • List(ArrayList,LinkedList)
      • Set(HashSet,TreeSet,LinkedHashSet)
      • Queue(PriorityQueue)
      • Stack(Stack)
    • Nepodporuje
      • Map
      • Element Removal
  • Iterator
    • Podporuje
      • List(ArrayList,LinkedList)
      • Set(HashSet,TreeSet,LinkedHashSet)
      • Queue(PriorityQueue)
      • Stack(Stack)
      • Map (nutno použít keySet().iterator, values().iterator nebo entrySet().iterator)
      • Element Removal
Input/Output and Streams in Java

Vamos praticar!

Input/Output and Streams in Java

Preparing Video For Download...