Home » Programming Languages » JAVA Programs » How to iterate through List in Java ?

How to iterate through List in Java ?

Lists are an ordered collection of elements in Java. Conceptually those are similar to Linked list in C with methods to add, delete elements. In this post, we are only going to look at how to iterate the through Lists in Java.

Method 1: Lets create and iterate simple ArrayList using for loop

List<String> myList = new ArrayList<String>();

myList.add("Hello");
myList.add("How");
myList.add("are")
myList.add("you?")

for (String listElement : myList) {
    System.out.println(listElement);
}

Method 2 : Using Iterator / ListIterator

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

List<String> myList = new ArrayList<String>();

myList.add("Hello");
myList.add("How");
myList.add("are")
myList.add("you?")

ListIterator<String> mIterator = myList.listIterator();

while(mIterator.hasNext()) {
    System.out.println(mIterator.Next());
}

Reference : https://docs.oracle.com/javase/8/docs/api/java/util/List.html


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment