Write a Java program to iterate through all elements in a linked list starting at the specified position


This Java code demonstrates how to use the listIterator(int index) method to iterate over a linked list starting from a specified position.

  • The code defines a class named Iterate_Specified_position with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a new LinkedList object named book_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Java", "C", "Cpp", etc., are added to the book_list using the add method, which appends the elements to the end of the list.
  • The System.out.println statement is used to print the initial contents of the book_list before any modifications.
  • The listIterator(int index) method is called on the book_list to obtain an iterator that allows iterating over the elements of the list starting from a specified position, indicated by the index parameter. In this case, the index is set to 3, which means the iterator will start from the fourth element (0-based index) of the list.
  • Inside the while loop, the b.hasNext() method is called to check if there are more elements in the iterator. If true, the b.next() method is called to retrieve the next element from the iterator, and it is printed using the System.out.println statement.
  • The loop continues until there are no more elements in the iterator, effectively iterating over the book_list starting from the specified position.
  • The output of the program will be the initial contents of the book_list printed on the first line, followed by the elements of the list starting from the specified position, each on a separate line.

Source Code

import java.util.LinkedList;
import java.util.Iterator;
public class Iterate_Specified_position
{
	public static void main(String[] args)
	{
		LinkedList<String> book_list = new LinkedList<String>();
		book_list.add("Java");
		book_list.add("C");
		book_list.add("Cpp");
		book_list.add("Python");
		book_list.add("Php");
		book_list.add("Css");
		book_list.add("Html");
		book_list.add("MySql");
		Iterator b = book_list.listIterator(3);
		while (b.hasNext())
		{
			System.out.println(b.next());
		}
	}
}

Output

Python
Php
Css
Html
MySql

Example Programs