← Back to Core Java Course | Chapter 11: Collections | Lesson 15 of 17

Java का Iterator

एक Iterator किसी collection में एक समय में एक item से चलता है, एक list के साथ move होती एक finger जैसा। यह items को safely remove भी कर सकता है जैसे यह आगे बढ़ता है।
Syntax
java
Iterator<Type> iterator = collection.iterator();
while (iterator.hasNext()) {
    Type item = iterator.next();
}

Introduction to Iterator

Iterator किसी भी collection में एक समय में एक element step through करने का एक uniform तरीका प्रदान करता है hasNext() और next() के ज़रिए, बिना यह जानने की ज़रूरत के कि underlying collection एक List, Set, या कुछ और है।

उदाहरण: Introduction to Iterator

java
// Import java.util.ArrayList so it can be used by its short name
import java.util.ArrayList;
// Import java.util.Iterator so it can be used by its short name
import java.util.Iterator;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new ArrayList object and store it in list
		ArrayList<String> list = new ArrayList<>(java.util.List.of("a", "b"));
		Iterator<String> it = list.iterator();
		// Repeat while it.hasNext() is true
		while (it.hasNext()) {
			// Print a line to the console
			System.out.println(it.next());
		}
	}
}

Removing Elements with Iterator

Iteration के दौरान iterator.remove() call करना underlying collection से current element सुरक्षित रूप से delete करता है — यह loop करते हुए elements हटाने का इकलौता safe तरीका है, क्योंकि collection को mid-loop सीधे modify करना एक ConcurrentModificationException throw करता है।

उदाहरण: Removing Elements with Iterator

java
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<>(java.util.List.of(1, 2, 3, 4));
		Iterator<Integer> it = list.iterator();
		while (it.hasNext()) {
			if (it.next() % 2 == 0) {
				it.remove(); // safe removal during iteration
			}
		}
		System.out.println(list);
	}
}

Iterator on Set

एक Set के पास कोई indexed access नहीं, इसलिए Iterator अक्सर order में हर element visit करने का इकलौता practical तरीका है, क्योंकि आप एक List की तरह एक traditional indexed for loop उपयोग नहीं कर सकते।

उदाहरण: Iterator on Set

java
import java.util.HashSet;
import java.util.Iterator;
public class Main {
	public static void main(String[] args) {
		HashSet<String> set = new HashSet<>(java.util.List.of("a", "b"));
		Iterator<String> it = set.iterator(); // no indexed access on a Set
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

ListIterator (Bidirectional)

ListIterator पीछे move करने (hasPrevious()/previous()) और mid-traversal elements replace या insert करने की क्षमता के साथ Iterator extend करता है, capabilities जो plain Iterator नहीं देता।

उदाहरण: ListIterator (Bidirectional)

java
import java.util.ArrayList;
import java.util.ListIterator;
public class Main {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>(java.util.List.of("a", "b"));
		ListIterator<String> it = list.listIterator();
		while (it.hasNext()) it.next();
		while (it.hasPrevious()) {
			System.out.println(it.previous()); // moves backward
		}
	}
}

Safe Modification

Iterating करते समय iterator के खुद के methods के अलावा किसी और तरीके से एक collection modify करना (जैसे एक for-each loop के अंदर सीधे list.remove() call करना) ConcurrentModificationException throw करता है — safe mutation के लिए हमेशा iterator के through ही जाएं।

उदाहरण: Safe Modification

java
import java.util.ArrayList;
public class Main {
	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<>(java.util.List.of(1, 2, 3));
		try {
			for (Integer n : list) {
				list.remove(n); // direct modification during for-each
			}
		} catch (java.util.ConcurrentModificationException e) {
			System.out.println("Caught: " + e.getClass().getSimpleName());
		}
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. next() से पहले remove() call करना, जो IllegalStateException throw करता है।
  2. जब hasNext() false हो तो next() call करना, जो NoSuchElementException throw करता है।
  3. एक iterator उपयोग करते समय collection को सीधे modify करना, जो ConcurrentModificationException throw करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.