Skip to main content

Different ways to iterate ArrayList in Java

How to Iterate ArrayList in Java

In this article, we are going to learn about how to iterate ArrayList in Java. Java provides various ways to loop over the ArrayList that we are going to see one-by-one.

What is ArrayList in Java

ArrayList in Java is a List in which we can store and retrieve elements like an array but it provides a facility of Dynamic array or Resize-able Array i.e., An array which can grow and shrink its size at the time of addition or deletion of elements. To know more about the ArrayList, read this article: ArrayList in Java.

How to Iterate ArrayList in Java using Iterator?

ArrayList provides a method called iterator() which returns an object of Iterator. Iterator is an interface defined in java.util package and its implementation are provided by the ArrayList internally.
Look at the Syntax of how to get the object of Iterator from the ArrayList:
Syntax of iterator() method
Iterator<T> iterator = arrayList.iterator();
By using this iterator object, we can iterate ArrayList in Java. Iterator provides two methods to iterate ArrayList in java are:
  • hasNext() : returns true, if iterator has more elements for iteration.
  • next() : returns the next element from the Iterator.
With the combination of these two methods, we can iterate ArrayList in Java.

Java ArrayList Iterator Example 1: Iterate ArrayList using Iterators

ArrayList<String> bookList = new ArrayList<>();
bookList.add("Programming In Java");
bookList.add("Introduction to Algorithms");
bookList.add("Data Structures");
bookList.add("Learn C++");
bookList.add("Computer Networks");

Iterator<String> iterator = bookList.iterator();

while (iterator.hasNext()) {
      String nextElement = iterator.next();
      System.out.println(nextElement);
}
Output
Programming In Java
Introduction to Algorithms
Data Structures
Learn C++
Computer Networks

Exceptional Case

Any addition or deletion of elements onto the ArrayList during the Iteration is not allowed. In such cases, java.util.ConcurrentModificationException will be raised. Just look at the example:
Iterator<String> iterator = bookList.iterator();

while (iterator.hasNext()) {
      String nextElement = iterator.next();

      // ConcurrentModificationException will be raised 
      bookList.add("Add new Element to the List"); 

      System.out.println(nextElement);
}
Output
Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909
        at java.util.ArrayList$Itr.next(ArrayList.java:859)
        at prac.code.ArrayListExample.main(ArrayListExample.java:56)

How to Iterate ArrayList in Java using for each loop?

ArrayList in Java implements Iterable Interface and any class whose implements Iterable interface can be iterate using for-each loop. Let's look at the example:

Java ArrayList Iterator Example 2: Iterate ArrayList using for-each loop

ArrayList<String> bookList = new ArrayList<>();
bookList.add("Programming In Java");
bookList.add("Introduction to Algorithms");
bookList.add("Data Structures");
bookList.add("Learn C++");
bookList.add("Computer Networks");

for(String book : bookList){
      System.out.println(book);
}

Output
Programming In Java
Introduction to Algorithms
Data Structures
Learn C++
Computer Networks
Note: Similar to Iterators, Any Addition or Modification of the elements into the ArrayList during Iteration is not allowed. In such cases, java.util.ConcurrentModificationException will be raised.

How to Iterate ArrayList in Java using forEach() method?

Since Java 8, a new method is added to the ArrayList which is forEach() method and this method can be used to iterate ArrayList in Java. The forEach() method takes an argument of the Consumer Functional Interface. This consumer object is passed as an argument of the forEach() method and consumes each element of the ArrayList one-by-one.
How to create object of Consumer
Consumer<String> consumer = (String book) -> {
      System.out.println(book); 
}
Note: Above, Lambda Expression is used to create object of Consumer. If you don't know about what is lambda expression, read this post: Lambda Expression in Java
Let's look at the example to better understand:

Java ArrayList Iterator Example 3: Iterate ArrayList using forEach() method

ArrayList<String> bookList = new ArrayList<>();
bookList.add("Programming In Java");
bookList.add("Introduction to Algorithms");
bookList.add("Data Structures");
bookList.add("Learn C++");
bookList.add("Computer Networks");

bookList.forEach((String book) -> {
      System.out.println(book);
});

Output
Programming In Java
Introduction to Algorithms
Data Structures
Learn C++
Computer Networks
Note: Similar to Iterators, Any Addition or Modification of the elements into the ArrayList during Iteration is not allowed. In such cases, java.util.ConcurrentModificationException will be raised.

Conslusion

In this article, we have learned different ways to iterate ArrayList in java. Java 8 onwards, forEach() method is the best and easiest way to iterate ArrayList. Also, we have learned what we cannot do during the Iteration of ArrayList.

Related Posts:


Comments

Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

HashMap in Java

HashMap in Java In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.
What is HashMap in java? Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework. Time complexity of HashMap in Java? : Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost. Internal working of HashMap in java HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of…

ArrayList in Java

ArrayList in Java In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.
Table of ContentsWhat is ArrayList in Java?Hierarchy of the ArrayList in java?How to create objects of ArrayList in Java?How to create an ArrayList of Custom Objects?How to iterate ArrayList in Java?How to get the elements by index from ArrayList in Java?How to check whether an elements is stored in the ArrayList in Java?How to remove elements from the ArrayList in Java?Few more methods of ArrayList in Java?
What is ArrayList in Java? ArrayList in Java is a List in which we can store and retrieve elemen…