Iterators In Java

Java Iterator is being taught to us in order to fulfill our educational requirements.

Java Iterators

Java Iterators are objects that can be used to loop through collections, like ArrayLists and HashSets, in order to traverse through the collection of data.

Looping is technically called iteration, so “Iterator” is the technical term used for iteration or looping.

Iterators can be used by importing them from the java.util package.



Getting an Iterator

Any collection can be iterated using the iterator() method:

Java Iterator() Example1: 

// Iterator and LinkedList should be imported import java.util.LinkedList; import java.util.Iterator;public class Main { public static void main(String[] args) {// Make a collection LinkedList it_Firms_in_America= new LinkedList();it_Firms_in_America.add("Geomotiv"); it_Firms_in_America.add("Cyber Infrastructure Inc"); it_Firms_in_America.add("ScienceSoft USA Corporation"); it_Firms_in_America.add("NextBig Technology(NBT)"); // here we create an IteratorIterator mrx = it_Firms_in_America.iterator();// The first item from the LinkedList is printed by using the iterator System.out.println("First Company name: "+mrx.next()); } }

Similarly, We can print the first odd number from the HashSet given below using an Iterator:

Java Iterator() Example:2 

// Iterator and HashSet should be imported import java.util.HashSet; import java.util.Iterator;public class Main { public static void main(String[] args) {// Make a collection HashSet odd_Numbers= new HashSet();odd_Numbers.add(1); odd_Numbers.add(3); odd_Numbers.add(5); odd_Numbers.add(7); odd_Numbers.add(9); odd_Numbers.add(11);// An Iterator is declared hereIterator mrx =odd_Numbers.iterator();// Using the iterator, the first item from the HashSet is printed System.out.println("First Odd Number is : "+mrx.next()); } }

Java Iterator example


Looping Through Collection

The Iterator provides the hasNext() and next() methods for looping through a collection.

We can loop through the vowels of the Arraylist using Iterator’s hasnext() and next() methods:

Example: 

// Iterator and ArrayList should be imported import java.util.ArrayList; import java.util.Iterator;public class Main { public static void main(String[] args) {// Here we create a collection of vowels of English Language and store it in an ArrayListArrayList vowels= new ArrayList();vowels.add('A'); vowels.add('E'); vowels.add('I'); vowels.add('O'); vowels.add('U');// Here we initialized the iterator and name it as ampleIterator ample =vowels.iterator();// Using the iterator, to print all the characters from the ArrayListSystem.out.println("\nPrint Vowels: \n"); while(ample.hasNext()){ // hasNext methods works ,until the iterator finds the last character of the ArrayList System.out.println(ample.next()); } } }

If you want to loop through a HashSet of boolean values, follow the given example:

Example: 

// Iterator and HashSet is imported from java.util packageimport java.util.HashSet; import java.util.Iterator;public class Main { public static void main(String[] args) {// We create a Hashset object to store boolean values in it.HashSet boolean_values= new HashSet();boolean_values.add(false); boolean_values.add(true); boolean_values.add(true); boolean_values.add(false); boolean_values.add(true);// Here we initialized the iterator and name it as ampleIterator mrx =boolean_values.iterator();// Using the iterator, to print all the boolean elements from the HashSetSystem.out.println("\nPrint boolean_values: \n"); while(mrx.hasNext()){ // hasNext methods works ,until the iterator finds the last value of the HashSet System.out.println(mrx.next()); } } }

Reminder: The outcomes of the above example are true and false, as the HashSet only prints the distinct (Unique) values. If you find this concept challenging ,do refer to “Java HashSet”.


Remove() Items from Collection

A looping iterator is designed for easy manipulation of collections that it loops through. While looping, items can be removed from a collection using a method named as remove().

The following example illustrates the removing of even numbers less than or equal to 15 using the Iterator’s remove() method:

Java Iterator Remove() Example:1 

import java.util.HashSet; import java.util.Iterator;public class Main { public static void main(String[] args) { HashSet odd_nums = new HashSet();odd_nums.add(1); odd_nums.add(2); odd_nums.add(3); odd_nums.add(4); odd_nums.add(5); odd_nums.add(6); odd_nums.add(7); odd_nums.add(8); odd_nums.add(9); odd_nums.add(10); odd_nums.add(11); odd_nums.add(12); odd_nums.add(13); odd_nums.add(14); odd_nums.add(15);Iterator mrx = odd_nums.iterator(); while(mrx.hasNext()) { Integer ample = mrx.next(); if(ample % 2==0) { mrx.remove(); } } System.out.println(odd_nums); } }

Correspondingly, we can also remove all the odd numbers till 15 and can print the even numbers only using the remove() method inside the if condition:

Java Iterator Remove() Example:2 

import java.util.HashSet; import java.util.Iterator;public class Main { public static void main(String[] args) { HashSet even_nums = new HashSet();even_nums.add(1); even_nums.add(2); even_nums.add(3); even_nums.add(4); even_nums.add(5); even_nums.add(6); even_nums.add(7); even_nums.add(8); even_nums.add(9); even_nums.add(10); even_nums.add(11); even_nums.add(12); even_nums.add(13); even_nums.add(14); even_nums.add(15);Iterator mrx = even_nums.iterator(); while(mrx.hasNext()) { Integer ample = mrx.next(); if(ample % 2==1) { mrx.remove(); } } System.out.println(even_nums); } }

 

Important: It will be impossible to remove items using a for loop or a for-each loop since the collection size is changing while the loop is running.

Key Points:

  1. The Iterator is an interface introduced in Java 1.2’s Collection framework. The package java.util contains it.
  2. A Java Cursor is used for traversing collection objects.
  3. Iterators are used to iterate the components of collection objects one by one.
  4. Known as a universal cursor of Java due to its suitability for all Collection framework classes.
  5. READ and REMOVE operations are also supported by the Java Iterator.
  6. There are very few method names in the Iterator class as compared to the Enumeration Iterator class.

 

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *