Skip to content

Iterate Vector in Reverse Direction in Java Example

This example shows how to iterate Vector in reverse direction in Java. This example also shows how to iterate Vector in reverse or backward direction using the ListIterator and for loop.

How to iterate Vector in reverse direction in Java?

There are several ways using which we can iterate Java Vector in the backward direction as given below.

1. Using the for loop

We can use the simple for loop starting from the (vector size – 1) index to (0) index to iterate over elements of the Vector object in the reverse direction. We can get elements from Vector using the get method and an index.

Output

2. Using the ListIterator

The Vector class provides the listIterator method that accepts the starting position.

It returns a ListIterator over the vector elements starting at the specified index.

In order to iterate the vector in a backward direction, we need to pass the vector size to this method to position the cursor after the last element of the vector. So that when we call the previous method, the first element that is returned by it will be the last element of the vector object.

Output

3. Using the Apache Commons

If you are using the Apache Commons library in your project, you can also use the ReverseListIterator class to iterate the vector object in the reverse direction as given below.

Output

Please also visit how to iterate a List in reverse direction to know about more ways to do this.

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.