This post will discuss how to get an iterator to the specific element of a List in Java.

1. Using a ListIterator

The standard way to get an iterator to a specific element of a list in Java is using the listIterator() method of the List interface. This method returns a list iterator over the elements in this list, starting at the specified position in the list. The specified index indicates the index of the first element that would be returned by an initial call to next(). An initial call to previous() would return the element with the specified index minus one. The following code demonstrates its usage, using the listIterator() method that takes an index of the first element to be returned from the list iterator.

Download  Run Code

 
The ListIterator interface provides several methods to access and modify the elements of the list. For example, we can use hasNext() and hasPrevious() methods to check if there are more elements in either direction, and nextIndex() and previousIndex() methods to get the index of the next and previous elements. We can also use the add() method to insert a new element into the list between the element that will be returned by next() and the element that will be returned by previous().

Download  Run Code

2. Using an Iterator

We can write a custom routine to advance the iterator to a specific position. This can be achieved by using List.iterator() that returns an Iterator to access each element sequentially in forward direction. This iterator only allows removing elements during iteration. Here’s an example:

Download  Run Code

That’s all about getting an iterator to the specific element of a List in Java.