AbsractCollection iterator() Method in Java with Examples
The iterator() method of Java AbstractCollection is used to return an iterator of the same elements as that of the Collection. The elements are returned in random order from what was present in the Collection.
Syntax:
Iterator iterate_value = AbstractCollection.iterator();
Parameters: The function does not take any parameter.
Return Value: The method iterates over the elements of the Collection and returns the values(iterators).
Below programs illustrate the use of AbstractCollection.iterator() method:
Program 1:
import java.util.*;
import java.util.AbstractCollection;
public class AbstractCollectionDemo {
public static void main(String args[])
{
AbstractCollection<String>
abs = new TreeSet<String>();
abs.add( "Welcome" );
abs.add( "To" );
abs.add( "Geeks" );
abs.add( "4" );
abs.add( "Geeks" );
System.out.println( "Collection: " + abs);
Iterator value = abs.iterator();
System.out.println( "The iterator values are: " );
while (value.hasNext()) {
System.out.println(value.next());
}
}
}
|
Output:
Collection: [4, Geeks, To, Welcome]
The iterator values are:
4
Geeks
To
Welcome
Program 2:
import java.util.*;
import java.util.AbstractCollection;
public class AbstractCollectionDemo {
public static void main(String args[])
{
AbstractCollection<String>
abs = new ArrayList<String>();
abs.add( "Welcome" );
abs.add( "To" );
abs.add( "Geeks" );
abs.add( "4" );
abs.add( "Geeks" );
System.out.println( "Collection: " + abs);
Iterator value = abs.iterator();
System.out.println( "The iterator values are: " );
while (value.hasNext()) {
System.out.println(value.next());
}
}
}
|
Output:
Collection: [Welcome, To, Geeks, 4, Geeks]
The iterator values are:
Welcome
To
Geeks
4
Geeks
Last Updated :
26 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...