Here we are learning about the Iterator interface in java.
Iterator interface :-
- An iterator interface is used to iterate or traverse the collection of elements one by one.
- It is iterating the data only forward direction.
- After calling iterate method if we want to try add elements in ArrayList(), then we cannot add elements before while loop, we will get concurrent modification exception.
- itr.hasNext() method is checking that there are any elements right to cursor is available or not.
- It is containing three methods.
Syntax :- public boolean hasNext();
public object next();
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorDemo {
public static void main(String[] args) {
Listlist=new ArrayList();
list.add("abc");
list.add("xyz");
list.add("test");
System.out.println("Iterate list of data :- ");
Iterator itr=list.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Output :-
Iterate list of data :-
abc
xyz
test
Remove Elements: –
- We can modify collection during iteration using remove() method.
- Here inside if condition within while loop we are comparing the given element with iterate element, if
- it is equals then from remove() method, we are remove elements.
Syntax :- public default void remove();
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class RemoveIterateDemo {
public static void main(String[] args) {
Listlist=new ArrayList();
list.add("abc");
list.add("xyz");
list.add("test");
System.out.println("remove elements from list of data :- ");
Iterator itr=list.iterator();
while(itr.hasNext()) {
Object obj=itr.next();
if(obj.equals("xyz")) {
itr.remove();
}
}
System.out.println(list);
}
}
Output :-
remove elements from list of data :-
[abc, test]
ListIterator() method:-
- This class is extending the iterator interface.
- From this we can iterate the data in forward and backward direction.
- In order to iterate the data in reverse order we use hasPrevious() and previous()
- To use ListIterator, we first iterate the data from hashNext and next() method.
Syntas :- public interface ListIterator<E> extends Iterator<E>
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class ListIteratorDemo {
public static void main(String[] args) {
List list = new ArrayList();
list.add("abc");
list.add("xyz");
list.add("test");
// Now use list iterator
ListIterator itr = list.listIterator();
System.out.println("Traversing the list in forward direction:- ");
while (itr.hasNext()) {
System.out.println(itr.next());
}
System.out.println("Traversing the list in backward direction:- ");
while (itr.hasPrevious()) {
System.out.println(itr.previous());
}
}
}
Output :-
Traversing the list in forward direction:-
abc
xyz
test
Traversing the list in backward direction:-
test
xyz
abc