In this tutorial, we will learn about the Java ArrayList iterator() method, and learn how to use this method to get an iterator for the elements in this ArrayList, with the help of examples.

Java ArrayList iterator() method

ArrayList iterator() returns an iterator over the elements in this ArrayList in proper sequence.

Syntax

The syntax of iterator() method is

</>
Copy
ArrayList.iterator()

Returns

The method returns Iterator object with elements of type same as that of in ArrayList.

1. iterator() – Get iterator for given ArrayList

In this example, we will define a ArrayList of Strings and initialize it with some elements in it. We will get an iterator for the elements in the ArrayList and print some elements using this iterator object.

Java Program

</>
Copy
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

public class Example {  
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList("a", "b", "c"));
		Iterator<String> iterator = arrayList.iterator();
		System.out.println(iterator.next());
		System.out.println(iterator.next());
	}  
}

Output

a
b

2. iterator() – ArrayList of User-defined Objects

In this example, we will define a ArrayList of user-defined class Car and initialize it with some Car objects. We will get an iterator for the Car objects in the ArrayList using ArrayList iterator() method.

Java Program

</>
Copy
import java.util.ArrayList;
import java.util.Iterator;

public class Example {  
	public static void main(String[] args) {
		ArrayList<Car> arrayList = new ArrayList<Car>();
		arrayList.add(new Car(1, "Tesla"));
		arrayList.add(new Car(2, "BMW"));
		arrayList.add(new Car(3, "Toyota"));
		
		Iterator<Car> iterator = arrayList.iterator();
		Car car = iterator.next();
		System.out.println(car.id + " - " + car.name);
    }  
}

class Car {
	int id;
	String name;
	public Car(int id, String name) {
		this.id = id;
		this.name = name;
	}
}

Output

1 - Tesla

Conclusion

In this Java Tutorial, we have learnt the syntax of Java ArrayList iterator() method, and also learnt how to use this method with the help of examples.