What is the standard method used to traverse ArrayList?

Iterating over ArrayLists in Java

ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package.

With the introduction and upgradations in java versions, newer methods are being available as if we do see from Java8 perceptive lambda expressions and streams concepts were not available before it as it been introduced in java version8.

Methods:

  1. Using for loops
  2. Using while
  3. Using for-each loop
  4. Using Iterator
  5. Using Lambda expressions (after Java8 only)
  6. Using Enumeration interface

Let us discuss these methods of which straight away we can perceive starting three methods are simply the naive approaches and further onwards methods carry some optimization with them. Do remember here while traversing elements are lesser we generally tend to iterate via naive approach only else if the size of elements to be inserted is big then we do use optimal approaches. Let us wrap each of the above approaches quickly.

Method 1: Using for loop






// Java program to iterate over an ArrayList
// Using for loop
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating and initializing the ArrayList
// Declaring object of integer type
List<Integer> numbers = Arrays.asList(1, 2, 3,
4, 5, 6, 7, 8);
// Iterating using for loop
for (int i = 0; i < numbers.size(); i++)
// Printing and display the elements in ArrayList
System.out.print(numbers.get(i) + " ");
}
}
Output 1 2 3 4 5 6 7 8

Method 2: Using while loop




// Java Program to Illustrate ArrayList
// Using While Loop
// Importing required classes
import java.util.ArrayList ;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating and initializing the ArrayList
// Declaring object of integer type
ArrayList<Integer> al = new ArrayList<Integer>();
// Adding elements to ArrayList
// using add() method
al.add(3);
al.add(1);
al.add(7);
al.add(20);
al.add(5);
// Step 1: Setting and initializing a variable
// as per syntax of while loop
// Initially declaring and setting
int val = 0;
// Step 2: Condition
// Till our counter variable is lesser than size of
// ArrayList
while (al.size() > val) {
// Printing the element which holds above
// condition true
System.out.println(al.get(val));
// Step 3: Terminating condition by incrementing
// our counter in each iteration
val++ ;
}
}
}
Output 3 1 7 20 5

Method 3: Using for each loop




// Java Program to Iterate over Arraylist
// using for Each loop
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Declaring and initializing ArrayList
List<Integer> numbers
= Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
// For Each Loop for iterating ArrayList
for (Integer i : numbers)
// Printing the elements of ArrayList
System.out.print(i + " ");
}
}
Output 1 2 3 4 5 6 7 8

Method 4: Using Iterator




// Java program to iterate over an ArrayList
// Using Iterator
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Declaring and initializing ArrayList
List<Integer> numbers
= Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
// Iterating ArrayList using Iterator
Iterator it = numbers.iterator();
// Holds true till there is single element
// remaining in the list
while (it.hasNext())
// Print the elements of ArrayList
System.out.print(it.next() + " ");
}
}
Output 1 2 3 4 5 6 7 8

Method 5: Using Lambda expressions




// Java program to iterate over an arraylist
// using Iterator in Java8 with Lambda Expression
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Declaring and initializing ArrayList
// Custom input elements
List<Integer> numbers = Arrays.asList(1, 2, 3,
4, 5, 6, 7, 8);
// Printing numbers using lambda expressions
// been introduced later in java8
numbers.forEach(number->System.out.println(number));
}
}
Output 1 2 3 4 5 6 7 8

Method 6: Using Enumeration interface




// Java Program to Iterate over ArrayList elements
// Using Enumeration
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an ArrayList
ArrayList<Integer> al = new ArrayList<Integer>();
// Adding elements to ArrayList
al.add(34);
al.add(12);
al.add(34);
al.add(23);
al.add(54);
// Getting an enumeration object
Enumeration<Integer> e
= Collections.enumeration(al);
// Till elements are there
while (e.hasMoreElements())
// Print elements using nextElement() method
System.out.println(e.nextElement());
}
}
Output 34 12 34 23 54

Now it is a further additive to the article as we are done with discussing all methods that can be used to iterate over elements. Till now we have traversed over input elements only and have not seen the traversal what if we play with elements, so do we are considering

Example




// Java program to demonstrate Working of
// Iterator.remove() on Arraylist
// Importing utility classes
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
// Main class
public class GFG
{
// Main driver method
public static void main(String[] args)
{
// Creating a List with referenceto ArrayList
List<Integer> al = new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(30);
al.add(1);
al.add(2);
// Remove elements smaller than 10 using
// Iterator.remove()
Iterator itr = al.iterator();
while (itr.hasNext())
{
int x = (Integer)itr.next();
if (x < 10)
itr.remove();
}
System.out.println("Modified ArrayList : "
+ al);
}
}
Output Modified ArrayList : [10, 20, 30]

Removing Items during Traversal: It is not recommended to use ArrayList.remove() when iterating over elements. This may lead to ConcurrentModificationException (Refer to this for a sample program with this exception). When iterating over elements, it is recommended to use Iterator.remove() method.

This article is contributed by Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

What is the standard method used to traverse ArrayList?




Article Tags :
Java
Java-ArrayList
Java-List-Programs
Practice Tags :
Java

ArrayList iterator() method in Java with Examples

The iterator() method of ArrayList class in Java Collection Framework is used to get an iterator over the elements in this list in proper sequence. The returned iterator is fail-fast.

Syntax:

Iterator iterator()

Parameter: This method do not accept any parameter.

Return Value: This method returns an iterator over the elements in this list in proper sequence

Below examples illustrate the ArrayList.iterator() method:



Program 1:




// Java code to illustrate iterator()
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Create and populate the list
ArrayList<String> list
= new ArrayList<>();
list.add("Geeks");
list.add("for");
list.add("Geeks");
list.add("is");
list.add("a");
list.add("CS");
list.add("Students");
list.add("Portal");
// Displaying the list
System.out.println("The list is: \n"
+ list);
// Create an iterator for the list
// using iterator() method
Iterator<String> iter
= list.iterator();
// Displaying the values after iterating
// through the list
System.out.println("\nThe iterator values"
+ " of list are: ");
while (iter.hasNext()) {
System.out.print(iter.next() + " ");
}
}
}
Output: The list is: [Geeks, for, Geeks, is, a, CS, Students, Portal] The iterator values of list are: Geeks for Geeks is a CS Students Portal

Program 2:




// Java code to illustrate iterator()
import java.util.*;
public class GFG {
public static void main(String args[])
{
// Creating an empty ArrayList
ArrayList<Integer> list
= new ArrayList<Integer>();
// Use add() method to add
// elements into the list
list.add(10);
list.add(15);
list.add(30);
list.add(20);
list.add(5);
// Displaying the list
System.out.println("The list is: \n"
+ list);
// Create an iterator for the list
// using iterator() method
Iterator<Integer> iter = list.iterator();
// Displaying the values
// after iterating through the list
System.out.println("\nThe iterator values"
+ " of list are: ");
while (iter.hasNext()) {
System.out.print(iter.next() + " ");
}
}
}
Output: The list is: [10, 15, 30, 20, 5] The iterator values of list are: 10 15 30 20 5

What is the standard method used to traverse ArrayList?




Article Tags :
Java
Technical Scripter
Java-ArrayList
Java-Collections
Java-Functions
Technical Scripter 2018
Practice Tags :
Java
Java-Collections

1. Iterate ArrayList with ‘for loop’

Java program to iterate through an ArrayList of objects using the standard for loop.

ArrayList<String> namesList = new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") ); for(int i = 0; i < namesList.size(); i++) { System.out.println(namesList.get(i)); }

2. Iterate ArrayList with ‘for-each loop’

Java program to iterate through an ArrayList of objects using for-each loop.

ArrayList<String> namesList = new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") ); for(String name : namesList) { System.out.println(name); }

Java Program to Iterate over an ArrayList

In this example, we will learn to iterate over the elements of an arraylist in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

  • Java ArrayList Class
  • Java for Loop
  • Java for-each Loop
  • Java ListIterator Interface

Different Ways Of Iterating An ArrayList In Java :

You can iterate a given ArrayList in 4 different ways. They are,

a) Iteration Using Normal for loop.

b) Iteration Using Iterator Object.

c) Iteration Using ListIterator Object.

d) Iteration Using Enhanced for loop.

Below is thedetaildescription of all of the above methods.