In the previous article, we have discussed about Java LinkedList descendingIterator() Method with Examples
In this article we are going to see the use of Java LinkedList iterator() method along with suitable examples.
Java LinkedList listIterator() Method with Examples
This java.util.LinkedList.listIterator()
method is used to get an iterator to retrieve each element of the LinkedList in a proper order starting from the specified index position.
Syntax:
LinkedListName.listIterator(int index_position)
Where,
LinkedListName
refers to the name of your LinkedList.index_position
refers to the specified index of list from which you will iterate all the elements.
Let’s see different examples to understand it more clearly.
Example-1: Java LinkedList listIterator() Method – Example with String Type LinkedList
Approach:
- Create a new LinkedList of type String.
- Add string elements into the LinkedList using the add() method.
- Display the LinkedList elements.
- Create an object of Iterator.
- Use a while loop through LinkedList for iteration till it has all elements.
- Inside
iterator()
method there is some inbuild methods likehasNext()
to check next element exists or not andnext()
to access the next element. - Print the LinkedList.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create an LinkedList of string datatype LinkedList<String> l1 = new LinkedList<String>(); // Adding some elements to the LinkedList l1.add("Bus"); l1.add("Truck"); l1.add("Metro"); l1.add("Car"); l1.add("Auto"); l1.add("Train"); l1.add("Taxi"); l1.add("Flight"); // Prints the LinkedList elements System.out.println("The elements in the LinkedList are: "+l1); // Create an object of Iterator Iterator<String> iterate = l1.listIterator(2); System.out.print("LinkedList: "); // loop through LinkedList from the specified index till it has all elements while(iterate.hasNext()) { // next() method of Iterator to access next elements System.out.print(iterate.next()); System.out.print(" "); } } }
Output: The elements in the LinkedList are: [Bus, Truck, Metro, Car, Auto, Train, Taxi, Flight] LinkedList: Metro Car Auto Train Taxi Flight
Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.
Related Java Programs: