LinkedList ListIterator Java example
In this post we will see various LinkedList ListIterator Java examples.
ListIterator in LinkedList can be used to iterate a list from a specified position.
Method :
1 | public ListIterator<E> listIterator(int index) |
LinkedList ListIterator Java example
In the below example we have used ListIterator to iterate a whole list and also a part of the list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | package com.kscodes.collections.linkedList; import java.util.LinkedList; import java.util.ListIterator; public class ListIteratorExample { public static void main(String[] args) { LinkedList<String> linkedList = new LinkedList<>(); // Use add(E e) to add elements linkedList.add("Java"); linkedList.add("JSP"); linkedList.add("Spring MVC"); linkedList.add("Hibernate"); // Iterate LinkedList using ListIterator // We are using listIterator() , which will iterate the whole list. System.out.println("****Iterating LinkedList using ListIterator - Whole list"); ListIterator<String> listIterator1 = linkedList.listIterator(); while (listIterator1.hasNext()) { System.out.println(listIterator1.next()); } // Iterate LinkedList using ListIterator from a specific position // We are using listIterator(index) , which will iterate the list from a // specific position. // EXAMPLE : if we specify "2" then list starts from "Spring MVC" System.out.println("****Iterating LinkedList using ListIterator - Some part of the List"); ListIterator<String> listIterator2 = linkedList.listIterator(2); while (listIterator2.hasNext()) { System.out.println(listIterator2.next()); } } } |
Output
1 2 3 4 5 6 7 8 | ****Iterating LinkedList using ListIterator - Whole list Java JSP Spring MVC Hibernate ****Iterating LinkedList using ListIterator - Some part of the List Spring MVC Hibernate |