LinkedList implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue.
The class implements the Deque interface, providing first-in-first-out queue operations for add, poll, along with other stack and deque operations.
All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
Note that this implementation is not synchronized
. If multiple threads access a linked list concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.
Lets first instantiate and populate a LinkedList implementation which contains the names of top Bay Area’s Companies.
Java Code:
package crunchify.com.tutorials; import java.util.LinkedList; import java.util.ListIterator; /** * @author Crunchify.com * How to iterate through LinkedList in Java? */ public class CrunchifyLinkedListIterator { public static void main(String[] args) { LinkedList<String> linkedList = new LinkedList<String>(); linkedList.add("Paypal"); linkedList.add("Google"); linkedList.add("Yahoo"); linkedList.add("IBM"); linkedList.add("Facebook"); // ListIterator approach System.out.println("ListIterator Approach: =========="); ListIterator<String> listIterator = linkedList.listIterator(); while (listIterator.hasNext()) { System.out.println(listIterator.next()); } System.out.println("\nLoop Approach: =========="); // Traditional for loop approach for (int i = 0; i < linkedList.size(); i++) { System.out.println(linkedList.get(i)); } // Java8 Loop System.out.println("\nJava8 Approach: =========="); // forEach Performs the given action for each element of the Iterable until all elements have been processed or // the action throws an exception. linkedList.forEach(System.out::println); } }
Output:
ListIterator Approach: Paypal Google Yahoo IBM Facebook Loop Approach: Paypal Google Yahoo IBM Facebook Java8 Approach: Paypal Google Yahoo IBM Facebook