In Java, an Iterator is an interface that provides methods to iterate over any Collection. It allows you to traverse through a collection and remove elements from the collection.
Iterators are used to process collections of objects in a standardized way. They provide a way to access elements without exposing the underlying representation.
import java.util.*;
class IteratorExample {
public static void main(String args[]) {
List list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Console Output:
Apple Banana Cherry
Removing elements from a collection while iterating can lead to ConcurrentModificationException. Using Iterator's remove method prevents this issue.
import java.util.*;
class IteratorRemoveExample {
public static void main(String args[]) {
List list = new ArrayList<>();
list.add("Dog");
list.add("Cat");
list.add("Rabbit");
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
String animal = iterator.next();
if ("Cat".equals(animal)) {
iterator.remove();
}
}
System.out.println(list);
}
}
Console Output:
[Dog, Rabbit]
Sets do not maintain an order of elements, but you can still use an Iterator to traverse them.
import java.util.*;
class SetIteratorExample {
public static void main(String args[]) {
Set set = new HashSet<>();
set.add("Red");
set.add("Green");
set.add("Blue");
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Console Output:
Red Green Blue
While the for-each loop is simpler, it doesn't allow removal of elements during iteration. Iterator provides more control.
import java.util.*;
class IteratorVsForEach {
public static void main(String args[]) {
List list = new ArrayList<>();
list.add("X");
list.add("Y");
list.add("Z");
for (String s : list) {
System.out.println(s);
}
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Console Output:
X Y Z X Y Z
Maps require a different approach as they store key-value pairs. Use entrySet, keySet, or values for iteration.
import java.util.*;
class MapIteratorExample {
public static void main(String args[]) {
Map map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
Iterator> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = iterator.next();
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
}
Console Output:
1 = One 2 = Two 3 = Three
LinkedList allows bidirectional iteration using ListIterator, providing more flexibility.
import java.util.*;
class LinkedListIteratorExample {
public static void main(String args[]) {
LinkedList list = new LinkedList<>();
list.add("Monday");
list.add("Tuesday");
list.add("Wednesday");
ListIterator iterator = list.listIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Console Output:
Monday Tuesday Wednesday
Implementing your own Iterator can be useful when you need custom traversal logic for your data structures.
import java.util.*;
class CustomIterator implements Iterator {
private int[] numbers;
private int index;
public CustomIterator(int[] numbers) {
this.numbers = numbers;
this.index = 0;
}
@Override
public boolean hasNext() {
return index < numbers.length;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return numbers[index++];
}
}
class CustomIteratorExample {
public static void main(String args[]) {
int[] numbers = {10, 20, 30};
CustomIterator iterator = new CustomIterator(numbers);
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Console Output:
10 20 30
Iterators for concurrent collections like ConcurrentHashMap are fail-safe, meaning they don't throw ConcurrentModificationException.
import java.util.concurrent.*;
class ConcurrentIteratorExample {
public static void main(String args[]) {
ConcurrentHashMap map = new ConcurrentHashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Console Output:
A B C
Iterators can only move forward, and they do not support adding elements during iteration. For more complex operations, consider using ListIterator.
import java.util.*;
class IteratorLimitationsExample {
public static void main(String args[]) {
List list = new ArrayList<>();
list.add("Alpha");
list.add("Beta");
ListIterator listIterator = list.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
listIterator.add("Gamma");
}
System.out.println(list);
}
}
Console Output:
Alpha Beta [Alpha, Gamma, Beta, Gamma]
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies