In this post, we will see different ways to loop List in java like using iterator and for loop.
Using Iterator –
public class ListArrayIterator { public static void main(String[] args) { List<String> myList = new ArrayList<String>(); myList.add("ABC"); myList.add("DEF"); myList.add("GHI"); myList.add("JKL"); myList.add("MNO"); System.out.println(myList); Iterator<String> iterator = myList.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } } }
In this above example, we have created an object of ArrayList with String instances.
Then added values to List using add() method
Iterator() will return the elements and assign to iterator object, this object will call available methods to play with each elements from the collection (i.e List).
Iterator.hasNext() method will return true if the iteration has next value, and next() method will return the next value in the iteration.
Using advance for loop –
for(String str : myList) { System.out.println(str); }
String str will hold each value from the List myList and display the value.
Using for loop with index –
for(int i=0 ; i < myList.size() ; i++) { System.out.println(myList.get(i)); }
myList.size() returns the no. of Strings present in the List and we loop based on the size
For more core Java related posts, refer Java topics