Monday, August 30, 2021

How to Loop or Iterate an Arraylist in Java

There are many ways to loop or iterate an ArrayList in Java. We can use the simple for loop, for-each loop (advanced for loop) available from Java 5 onwards, iterator or ListIterator (though not a preferred way if we are just sequentially looping through the elements of a list) and from Java 8 using Java 8 forEach statement that works with stream.

So the options available to loop through an ArrayList in Java are-

  • for loop
  • for-each loop
  • iterator
  • ListIterator
  • Java 8 forEach loop

Java Example code to traverse an ArrayList

Let's see a program that will use all these ways to iterate an ArrayList in Java.

public class LoopListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    
    // Using for loop with size to iterate ArrayList
    System.out.println("With simple for loop");
    for(int i = 0; i < cityList.size(); i++){
      System.out.println("City Name - " + cityList.get(i));
    }
    
    // Using for-each loop to iterate ArrayList 
    System.out.println("With for-each loop - Java 5");
    for(String name : cityList){
      System.out.println("City Name - " + name);
    }
    
    // Using Iterator to iterate ArrayList
    System.out.println("With iterator - Java 5");
    Iterator<String> itr = cityList.iterator();
    while(itr.hasNext()){
      System.out.println("City Name - " + itr.next());
    }
    
    // Using List Iterator - though not needed if doing sequential looping
    System.out.println("With List iterator - Java 5");
    ListIterator<String> ltr = cityList.listIterator();
    while(ltr.hasNext()){        
      System.out.println("City Name - " + ltr.next());
    }
    
    //Using Java 8 iterable.forEach to iterate ArrayList
    System.out.println("With for-each loop - Java 8");
    
    cityList.forEach((a)->System.out.println("City Name - " + a));
    
    //Using Java 8 iterable.forEach loop with method reference
    cityList.forEach(System.out::println);
  }
}

Output (curtailed)

With simple for loop
City Name - Delhi
City Name - Mumbai
City Name - Bangalore
City Name - Chennai
City Name - Kolkata
With for-each loop - Java 5
City Name - Delhi
City Name - Mumbai
City Name - Bangalore
City Name - Chennai
City Name - Kolkata
With iterator - Java 5
City Name - Delhi
City Name - Mumbai
City Name - Bangalore
City Name - Chennai
City Name - Kolkata

In my opinion for-each loop is best way to iterate a list if you just need to traverse sequentially through a list.

With Java 8 and multi-core environment you can also use Java 8 forEach statement to take advantage of parallel computing using parallel stream. In that case you need to write it like-

cityList.parallelStream().forEach((a)->System.out.println("City Name - " + a));

That's all for this topic How to Loop or Iterate an Arraylist in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. ListIterator in Java
  3. How LinkedList Class Works Internally in Java
  4. How to Convert Array to ArrayList in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. How HashMap Works Internally in Java
  2. Fail-Fast Vs Fail-Safe Iterator in Java
  3. Java ArrayBlockingQueue With Examples
  4. Synchronization in Java - Synchronized Method And Block
  5. Interface Default Methods in Java
  6. Method Reference in Java
  7. Difference Between Checked And Unchecked Exceptions in Java
  8. Java Multi-Threading Interview Questions And Answers

2 comments:

  1. when to use iterator and for each loop in java.

    ReplyDelete
  2. for-each loop is best way to iterate a list if you are just traversing list sequentially, not trying to modify list (remove any element) as trying to modify will result in ConcurrentModificationException. If you have to remove any element too while traversing then use iterator and its remove method to avoid ConcurrentModificationException.

    ReplyDelete