Programming Tutorials

iterator() and hasNext() in Java

By: Baski in Java Tutorials on 2007-09-14  

In Java, iterator() and hasNext() are methods used for iterating over collections, such as lists, sets, and maps.

iterator() returns an iterator object that can be used to traverse the elements of the collection in forward direction. The Iterator interface provides methods such as next() to get the next element in the collection, and remove() to remove the current element.

For example, to use an iterator to traverse a list:

List list = new ArrayList<>();

Iterator iterator = list.iterator();
while (iterator.hasNext()) {
    String element =;

In this code, iterator() is called on the list object to get an iterator, which is then used in a while loop to iterate over the elements. The hasNext() method checks if there are more elements to iterate over, and next() returns the next element.

hasNext() returns a boolean indicating whether there are more elements in the collection to iterate over. This method is often used in conjunction with next() in a loop to iterate over all the elements in a collection.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)