Iterate through Vector in Java Example

This example shows how to iterate through Vector in Java. This example also shows how to iterate through Vector using for loop, iterator, enumeration, ListIterator, and Java 8 forEach.

How to iterate through Vector in Java?

There are several ways using which we can iterate through elements of Vector in Java as given below.

1. Using for loop

The simplest way is to use the for loop to iterate over elements from index 0 to vector size – 1 index and use the Vector get method to get the elements.


2. Using enhanced for loop

We can also use the enhanced for loop instead of the simple for loop as given below.


3. Using enumeration

The Vector elements method returns an enumeration of all the elements of this vector object. We can use this enumeration to iterate over elements of Vector using the hasMoreElements and nextElement methods along with the while loop.


4. Using Iterator

We can get an iterator over all elements of the vector using the iterator method. Once we get the iterator, we can iterate through it using the hasNext and next methods and the while loop.


5. Using ListIterator

We can also get an object of the ListIterator using the listIterator method of the Vector class. Once we get the list iterator, we can iterate it using the hasNext and next methods as given below.


6. Using forEach (Java 8)

If you are using Java version 8 or later, you can also use the forEach method to iterate over Vector elements as given below.


Please also visit how to iterate Vector in reverse order in Java example to know more.

This example is a part of the Vector in Java Tutorial with Examples.

Please let me know your views in the comments section below.

Java 8 Vector Documentation

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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

Online Shopping