How to get previous and next index using java List Iterator

The previous index and the next index in an ArrayList can be retrieved using the PreviousIndex() and nextIndex() methods in the ListIterator interface. previousIndex() can also return -1 if it is at the top of the list.

Example:

Input: list = [2, 3, 6, 8]
listiterator is at the beginning find previous index.
 
Output: -1

Input: list = [2, 3, 6, 8]
listiterator is at the beginning find next index.

Steps to use previousIndex() and nextIndex():

 

  • Create an empty ArrayList
  • Add elements to ArrayList.
  • Create a listiterator using listIterator() method.

 

Listiteratoriterator = arrList.listIterator();
  • Now get the required index using the below commands

Syntax

iterator.previousIndex();

Returns: the index of the element to be returned in the next call to the previous one, or -1 if the list iterator is at the beginning of the list

Syntax

iterator.nextIndex();

Returns: the index of the element to return on the next call, or the size of the list if the list iterator is at the end of the list

Example

// Java program to get Previous and
// next index using ListIterator

import java.io.*;
import java.util.ArrayList;
import java.util.ListIterator;

class PreviousAndNextIndex {
	
	public static void main(String[] args)
	{
		// create empty ArrayList
		ArrayList arrList
			= new ArrayList();
		
		// add elements to the ArrayList
		arrList.add(5);
		arrList.add(10);
		arrList.add(15);
		arrList.add(20);
		arrList.add(25);
		arrList.add(30);

		// print the initial list
		System.out.println("Initial arraylist =>"
						+ arrList);

		// initializing ListIterator
		ListIterator iterator
			= arrList.listIterator();

		// initially iterator is the beginning so
		// previousIndex() will return -1
		System.out.println("previous index =>"
						+ iterator.previousIndex());

		// from -1 moving iterator to the 1st index
		iterator.next();
		iterator.next();

		// now iterator is at 1st index
		// so nextIterator() will return 2
		System.out.println("Next index =>"
						+ iterator.nextIndex());
	}
}

Output:

Initial arraylist =>[5, 10, 15, 20, 25, 30]
previous index =>-1
Next index =>2

 

Submit Your Programming Assignment Details