Iterator Functions in Java


Iterator in Java is used to traverse each and every element in the collection. Using it, traverse, obtain each element or you can even remove. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.

Following are the Interator Functions in Java −

Modifier and TypeMethod & Description
default voidforEachRemaining(Consumer<? super E> action)
The forEachRemaiing() method performs the given action for each remaining element until all elements have been processed or the action throws an exception.
booleanhasNext()
The hashNext() method returns true if the iteration has more elements.
Enext()
The next() method returns the next element in the iteration.
default voidremove()
The remove() method removes from the underlying collection the last element returned by this iterator

The iterator() method is provided by every Collection class. To use an iterator to cycle through the contents of a collection, at first obtain an iterator to the start of the collection by calling the collection's iterator( ) method. After that, set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. At last, within the loop, obtain each element by calling next( ).

Let us now see an example to iterate through the values of ArrayList −

Example

import java.util.*;
public class Main {
   public static void main(String args[]) {
      ArrayList myList = new ArrayList();
      myList.add("Jack");
      myList.add("Nathan");
      myList.add("Tom");
      myList.add("Ryan");
      myList.add("David");
      myList.add("Kevin");
      myList.add("Steve");
      myList.add("Nathan");
      myList.add("Tim");
      System.out.print("Values
");       Iterator i = myList.iterator();       while(i.hasNext()) {          Object obj = i.next();          System.out.print(obj + " ");       }       System.out.println();    } }

Output

Values
Jack Nathan Tom Ryan David Kevin Steve Nathan Tim

Updated on: 24-Sep-2019

963 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements