Here Is 4 Ways To Print ArrayList Elements In Java

(Last Updated On: March 13, 2019)

Learn 4 Techniques to PRINT ArrayList Elements in Java with Code Example.

To print elements, first we’ll create a String ArrayList and store weekdays name as strings into it and display them using following ways:

  1. For-loop
  2. For-each loop
  3. Using iterator
  4. Using List-iterator

Here is a string ArrayList. We have created an object of the list and added name of week days using add() method of ArrayList.

 

PRINTING ARRAYLIST

1)Using for loop

To use for loop, we’re getting the length of the ArrayList using its size() method, up to which we need to retrieve elements. We have used get(i) method of the arraylist to fetch the data present at the indexes of the arraylist.

 

2)Using for-each loop

Here, the same for loop is written in another form using for each loop or advance loop method in java. This type of loop fetchs every elements from the arralist object one by one.

 

3)Using iterator

Iterators in java collection framework are used to retrieve elements one by one. ArrayList iterator() method returns an iterator for the list. The Iterator contains methods hasNext() that checks if next element is available. Another method next() of Iterator returns elements.

We have implemented while loop to traverse the ArrayList.  In the loop, we are checking if next element is available using hasNext() method. Iterator hasNext() methods returns the Boolean value  true or false. If hasNext() returns true, the loop fetchs the ArrayList elements using Iterator next() method and print it using System.out.println mehtod. If hasNext() returns false, there is no further elements in the list.

 

4)Using list-iterator

We can also use ListIterator to traverse elements of the ArrayList. ListIterator also has methods hasNext() to check if element is present and next() method to retrieve ArrayList elements. ListIterator is similar to iterator with difference that iterator is unidirectional and ListIterator is bidirectional.

The only thing in case of list iterator is that we have to initialize it with null at first.

ListIterator<String> litr = null;

 

Complete Code to print ArrayList Elements in Java using all 4 Ways

The complete code to print all elements of the ArrayList using all 4 techniques is given below:

 

Output
Using For Loop

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Using for-each loop

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Using Iterator
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Using list iterator
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday