ArrayList iterator() method in Java with Examples
The iterator() method of ArrayList class in Java Collection Framework is used to get an iterator over the elements in this list in proper sequence. The returned iterator is fail-fast.
Syntax:
Iterator iterator()
Parameter: This method do not accept any parameter.
Return Value: This method returns an iterator over the elements in this list in proper sequence
Below examples illustrate the ArrayList.iterator() method:
Program 1:
import java.util.*;
public class GFG {
public static void main(String[] args)
{
ArrayList<String> list
= new ArrayList<>();
list.add( "Geeks" );
list.add( "for" );
list.add( "Geeks" );
list.add( "is" );
list.add( "a" );
list.add( "CS" );
list.add( "Students" );
list.add( "Portal" );
System.out.println( "The list is: \n"
+ list);
Iterator<String> iter
= list.iterator();
System.out.println( "\nThe iterator values"
+ " of list are: " );
while (iter.hasNext()) {
System.out.print(iter.next() + " " );
}
}
}
|
Output:
The list is:
[Geeks, for, Geeks, is, a, CS, Students, Portal]
The iterator values of list are:
Geeks for Geeks is a CS Students Portal
Program 2:
import java.util.*;
public class GFG {
public static void main(String args[])
{
ArrayList<Integer> list
= new ArrayList<Integer>();
list.add( 10 );
list.add( 15 );
list.add( 30 );
list.add( 20 );
list.add( 5 );
System.out.println( "The list is: \n"
+ list);
Iterator<Integer> iter = list.iterator();
System.out.println( "\nThe iterator values"
+ " of list are: " );
while (iter.hasNext()) {
System.out.print(iter.next() + " " );
}
}
}
|
Output:
The list is:
[10, 15, 30, 20, 5]
The iterator values of list are:
10 15 30 20 5
Last Updated :
11 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...