There are different ways by which we can traverse over elements that are for-loop, while loop, do-while, for each loop etc. They all are index based on traversing methods. But as we know Java is purely object oriented programming language in which we always have possible ways of doing things using objects. So Iterator is a way to traverse the data over the collection objects.
Java Iterator is an Interface that belongs to the collection framework allow us to traverse the collection objects and access the elements of that collection. Basically List Interface and Set Interface provides the iterator. Iterator can be used with all the implementation of Set and List Interfaces like for example ArrayList, LinkedList, TreeSet etc.
Map implementation such as HashMap, TreeMap, LinkedHashMap doesn’t provide Iterator directly but we can iterate over them by getting there key-Set or Value Set.
Table of Contents
1. boolean hasNext( )
This method returns true if there are more elements else it returns false.
2. Object next( )
This method returns the next element in the collection or else throws NoSuchElementException if there is no next element present.
3. void remove( )
This method removes the current element on which iteretor points to or else throws IllegalStateException if remove( ) method is called that is not preceded by a call to next( ) method.
1. fail-fast Iterator
As name suggests fail-fast Iterator fails as soon as the structure of Collection has been changed since traversing has begun. Changes means adding, removing or updating any element from collection while one thread is Iterating over that collection.
fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws ConcurrentModificationException.
2. fail-safe Iterator
Contrary to fail-fast Iterator, fail-safe iterator doesn’t throw any Exception if Collection is modified structurally while one thread is traversing over it as they work on copy of Collection instead of original collection and that is why, they are called as fail-safe iterator.
Every collection class has an iterator() method which returns an iterator object to the beginning of the collection elements. By using this object, we can access each element in the collection and each element at a time.
To use an Iterator to traverse the collection follow these steps:
1. Obtain an Iterator by calling the collection’s iterator( ) method.
2. Create a loop that makes a call to hasNext( ) method.
3. Iterate the loop as long as hasNext() method returns true.
4. In the loop get each element by calling next( ) method.
Example of How to use Iterator with List Interface in Java:
Let us discuss Iterator with List Interface with the help of program, following program has been divided into 3 Steps that we will discuss one by one:
import java.util.*; public class IteratorExampleDemo{ public static void main(String[] args) { //Step 1: create an ArrayList List<String> arrayList = new ArrayList<String>(); //Step 2: Add elements in Array List arrayList.add("I"); arrayList.add("Love"); arrayList.add("JAVA"); System.out.println("Iterate Using Iterator"); //Step 3: Iterator object of String type is created Iterator<String> iterator = arrayList.iterator(); //Step 4: Iterate Using while loop while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
Output:
Iterate Using Iterator I Love JAVA
Description:
Example of How to use Iterator with Set Interface in Java:
Let us discuss Iterator with Set Interface with the help of program, following program has been divided into 4 Steps that we will discuss one by one.
import java.util.*; public class IteratorExampleDemo{ public static void main(String[] args) { //Step 1: create an hashSet Set<String> hashSet = new HashSet<String>(); //Step 2: Add elements in hash Set hashSet.add("I"); hashSet.add("Love"); hashSet.add("JAVA"); System.out.println("Iterate Using Iterator"); // Step 3: Iterator object of String type is created Iterator<String> iterator = hashSet.iterator(); //Step 4: Iterate Using while loop while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
Output:
Iterate Using Iterator JAVA Love I
Description:
Example of How to use Iterator with Map Interface in Java:
Iterating over any of the Map implementations like Hashmap, TreeMap etc is not very straight forward as compared to other collections. Let us discuss Iterator with Map Interface with the help of program, following program has been divided into 4 Steps that we will discuss one by one
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class IteratorMapExample { public static void main(String[] args) { //Step 1: Object of HahsMap class is Created Map hashMapObj = new HashMap<String, String>(); //Step 2: values are added using put() method hashMapObj.put("Abhishek", "A+"); hashMapObj.put("Gaurav", "B+"); hashMapObj.put("Pryanka", "A-"); hashMapObj.put("Rahul", "B+"); System.out.println("Using Iterator"); //Step 3: object of Iterator is Created Iterator<Map.Entry<String, String>> iterator = hashMapObj.entrySet().iterator() ; //Step 4: Traveresed Using While loop while(iterator.hasNext()){ Map.Entry<String, String> bloodGroup = iterator.next(); System.out.println(bloodGroup.getKey() +" :: "+ bloodGroup.getValue()); } } }
Output:
Using Iterator Rahul :: B+ Abhishek :: A+ Gaurav :: B+ Pryanka :: A-
Description:
Both Iterator and Enumerator is used for traversing the collection, then why we need Iterator? Following points will tell why we need Iterator:
Premium Project Source Code: