BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to loop ArrayList in Java

Last Updated: December 1, 2024 by Chaitanya Singh | Filed Under: java

In this guide, you will learn how you can loop through an ArrayList in Java. In the ArrayList tutorial, we learned that it belongs to java.util package and unlike arrays, it can grow in size dynamically. There are several different approaches to iterate an ArrayList, lets discuss them with examples:

1. Using a for Loop

One of the easiest way to iterate through an ArrayList is by using for loop:

import java.util.ArrayList;

public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Chaitanya");
names.add("Rahul");
names.add("Aditya");

// names.size() returns size of ArrayList and get()
// method returns the element present at specified index
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
}
}

2. Using an Enhanced for Loop (for-each)

The enhanced for loop provides a simple and more readable way to iterate through all the elements in an ArrayList. Let’s take the same example that we have seen above but with for-each loop instead of for loop.

import java.util.ArrayList;

public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Chaitanya");
names.add("Rahul");
names.add("Aditya");

for (String name : names) {
System.out.println(name);
}
}
}

3. Using an Iterator

One of the limitations with for-each loop is that you cannot remove an element while iterating. An Iterator provides a way to iterate a collection, and it allows you to remove an element while iterating.

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Chaitanya");
names.add("Rahul");
names.add("Aditya");

Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

4. Using a ListIterator

A ListIterator allows you to traverse the list in both directions. You can also modify the list during iteration:

import java.util.ArrayList;
import java.util.ListIterator;

public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Chaitanya");
names.add("Rahul");
names.add("Aditya");

ListIterator<String> listIterator = names.listIterator();
// Traversing forward
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}

// Traversing backward
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}

5. Using Streams (Java 8 and later)

Stream API is introduced in Java 8. I have covered it in detail here: Java 8 Streams Tutorial. You can also loop through an ArrayList elements using stream.

import java.util.ArrayList;

public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Chaitanya");
names.add("Rahul");
names.add("Aditya");

names.stream().forEach(System.out::println);
}
}
❮ Java ArrayList

Top Related Articles:

  1. How to sort Hashtable in java
  2. StringJoiner toString() Method in Java
  3. ArrayList in Java With Examples
  4. Examples of throws Keyword in Java
  5. How to Convert an array to ArrayList in java

Tags: Collections, Java-ArrayList

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Govardhan says

    November 16, 2014 at 5:42 AM

    sir how to iterate arraylist elements using Enumeration interface

    Reply
    • Chaitanya Singh says

      November 18, 2014 at 4:48 AM

      Hi Govardhan,

      I have updated the post and added the code. You can find your answer above in the post. Let me know if you have any further question.

      Reply
      • Govardhan says

        December 5, 2014 at 3:14 PM

        sir I have one more question:=
        1.How to find middle value of a linked list by single pass

        Reply
        • srinath says

          December 20, 2014 at 2:35 AM

          Use two variable, lets call them fastVariable and slowVariable.

          Move the fastVariable twice the speed of slowVariable.

          By the time fastVariable reach end of the list slowVariable will be at middle of the list.

          Thanks.

          Reply
  2. David tolu says

    November 30, 2014 at 7:25 PM

    how to detect duplicate values in an arrayList?

    Reply
  3. Melly says

    April 16, 2018 at 1:14 AM

    Hello!

    So I have two seperate arraylists. I am trying to display both of them on a form, but only one of them is showing up. Is it possible to loop to arrayLists and display them at the same time?

    Reply
    • Chaitanya Singh says

      April 19, 2018 at 12:05 PM

      Melly, You can join both the arraylists and then loop the combined arraylist to display all the elements. Refer this: How to join ArrayList?

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap