HomeCore JavaJava ListIterator guide + Examples

Java ListIterator guide + Examples

Java ListIterator allows the programmers to traverse the list in either direction, modify the list during iteration, and obtain iterator’s current position.

Java ListIterator is the child interface of Iterator. While iterating by Iterator we can perform only read and remove operations and we can’t perform update and add new objects operations. ListIterator overcome this limitation.

1. Java ListIterator methods

  1. void add(E element) – Inserts the specified element into the list (optional operation).
  2. boolean hasNext() – Returns true if this list iterator has more elements when traversing the list in the forward direction.
  3. boolean hasPrevious() – Returns true if this list iterator has more elements when traversing the list in the reverse direction.
  4. E next() – Returns the next element in the list and advances the cursor position.
  5. int nextIndex() – Returns the index of the element that would be returned by a subsequent call to next().
  6. E previous() – Returns the previous element in the list and moves the cursor position backwards.
  7. int previousIndex() – Returns the index of the element that would be returned by a subsequent call to previous().
  8. void remove() – Removes from the list the last element that was returned by next() or previous() (optional operation).
  9. void set(E e) – Replaces the last element returned by next() or previous() with the specified element (optional operation).

2. ListIterator example 1

Following example demonstrates how to retrieve list elements using ListIterator and removing elements while iterating.

public class RemoveElementsWhileIteratingDemo {

	public static void main(String[] args) {
		
		List<String> l = new ArrayList<>();
	
		l.add("Peter");
		l.add("Martin");
		l.add("Mike");
		l.add("John");
		l.add("Gerhard");
		System.out.println(l); //[Peter, Martin, Mike, John, Gerhard]
		
		// obtaining list iteraor
		ListIterator<String> i = l.listIterator();
		
		// Remove name if starts with "P"
		while (i.hasNext()) {
			String name = i.next();
			
		    if(!name.startsWith("P"))
		    	System.out.println(name);
		    else
		    	i.remove();
		}
		System.out.println(l);
	}
}

Output :

[Peter, Martin, Mike, John, Gerhard]
Martin
Mike
John
Gerhard
[Martin, Mike, John, Gerhard]

3. ListIterator Example 2 add and update values while iterating

Following example demonstrates how to add or update list elements while iterating and get previous and next element indexes.

public static void main(String[] args) {
		
		List<String> l = new ArrayList<>();
	
		l.add("Peter");
		l.add("Martin");
		l.add("Mike");
		l.add("John");
		l.add("Gerhard");
		System.out.println(l); //[Peter, Martin, Mike, John, Gerhard]
		
		// obtaining list iteraor
		ListIterator<String> i = l.listIterator();
		
		// Remove name if starts with "P"
		while (i.hasNext()) {
			String name = i.next();
			
		   if(name.equals("Peter"))
			   i.set(name.toUpperCase());
		  
		   if(name.contains("John"))
			   i.add("Abraham");
		   
		   if(i.hasPrevious())
			   System.out.print("[Previous Index: "+ i.previousIndex()+"]");
		   
		   if(i.hasNext())
			   System.out.print(" [Next Index: "+ i.nextIndex()+"]\n");
		}
		
		System.out.println("\nFinal List "+l);
	}
}

Output :

[Peter, Martin, Mike, John, Gerhard]
[Previous Index: 0] [Next Index: 1]
[Previous Index: 1] [Next Index: 2]
[Previous Index: 2] [Next Index: 3]
[Previous Index: 4] [Next Index: 5]
[Previous Index: 5]
Final List [PETER, Martin, Mike, John, Abraham, Gerhard]

4. Limitations of ListIterator

ListIterator has many features like, we can add, update, remove elements while iterating and also backward and forward navigation possible to get previous and next elements and their indexes while iterating. Java Enumeration and Java Iterator doesn’t have these features (only remove feature is there using Iterator while iterating).

Although ListIterator has many features we can apply only for List implementation classes, this is not universal cursor to apply for any collection.

5. Conclusion

In this article we have covered about Java ListIterator, how to retrieve elements from list using ListIterator, how to remove or add or update elements of list iterator while iterating.

References

  1. Java Document
  2. Java Iterator interface
  3. Java Enumerator interface

LEAVE A REPLY

Please enter your comment!
Please enter your name here