Retrieving Elements from Collections in Java
Retrieving Elements from Collections
- Using for-each loop
- Using Iterator inteface
- Using ListIterator interface
for-each Loop
for-each loop is like for loop which repeatedly executes a group of statements for each element of collection.The syntax of for-each loop is:
for(variable: collection-object)
{
Statements;
}
Note: Here, the variable assumes each element of the collection-object and the loop is executed as many times as there are number of elements in the collection-object.
Iterator Interface
Iterator is an interface that contains methods to retrieve the elements one by one from a collection object.It has three methods:
- boolean hasnext(): This method returns true if the the iterator has more elements.
- element next(): This method returns the next element in the iterator.
- void remove(): This method removes from the collection the last element returned by the iterator.
ListIterator Interface
ListIterator is an interface that contains methods to retrieve the elements from a collection object, both in forward and reverse direction.It has the following methods:
- boolean hasnext(): This method returns true if the the ListIterator has more elements when traversing the list in the forward direction.
- boolean hasPrevious(): This method returns true if the ListIterator has more elements when traversing the list in the reverse direction.
- element next(): This method returns the next element in the list.
- element previous(): This method returns the previous element in the list.
- void remove(): This method removes from the list the last element that was returned by the next() or previous() methods.