Iterator
Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection.
interface Iterator<E>
E specifies the type of objects being iterated.
It defines the following methods:
boolean hasNext( )
- Returns true if there are more elements. Otherwise, returns false.
E next( )
- Returns the next element. Throws NoSuchElementException if there is not a next element.
void remove( )
- Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).
By using this iterator object, you can access each element in the collection, one element at a time.
import java.util.Iterator;
import java.util.LinkedList;
public class Main{
public static void main(String args[]) {
LinkedList<String> ll = new LinkedList<String>();
ll.add("A");
ll.add("ja v a2s.com");
ll.addLast("B");
ll.add("C");
Iterator<String> itr = ll.iterator();
while (itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
}
}
The output:
A ja v a2s.com B C
Remove an element from Collection using Iterator
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList aList = new ArrayList();
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("java2 s .com");
System.out.println("ArrayList: ");
System.out.println(aList);
Iterator itr = aList.iterator();
String strElement = "";
while (itr.hasNext()) {
strElement = (String) itr.next();
if (strElement.equals("2")) {
itr.remove();
break;
}
}
System.out.println("ArrayList after removal : ");
System.out.println(aList);
}
}
The output:
ArrayList:
[1, 2, 3, 4, java2 s .com]
ArrayList after removal :
[1, 3, 4, java2 s .com]
Because all of the collection classes implement this interface, they can all be operated upon by the for. for can cycle through any collection of objects that implement the Iterable interface.
import java.util.ArrayList;
public class Main {
public static void main(String args[]) {
ArrayList<Integer> vals = new ArrayList<Integer>();
vals.add(1);
vals.add(2);
vals.add(3);
vals.add(4);
vals.add(5);
for (int v : vals){
System.out.println(v + " ");
}
int sum = 0;
for (int v : vals){
sum += v;
}
System.out.println("Sum of values: " + sum);
}
}