Skip to content

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.

Output

2. Using enhanced for loop

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

Output

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.

Output

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.

Output

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.

Output

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.

Output

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.

References:
Java 8 Vector Documentation

About the author

Leave a Reply

Your email address will not be published.