if I use a for-each loop on a linked list in java, is it guaranteed that I will iterate on the elements in the order in which they appear in the list?
Using enhanced for loop we can sequentially iterate a LinkedList. The execution of the enhanced for loop ends after we visit all the elements. Let us see an example of iterating the LinkedList using the enhanced for loop.
Syntax: ListIterator new_list = LinkedList. listIterator(int index); Parameters: The parameter index is an integer type value that specifies the position of the element from where ListIterator starts operating and returning values.
I found 5 main ways to iterate over a Linked List in Java (including the Java 8 way):
For loop
LinkedList<String> linkedList = new LinkedList<>(); System.out.println("==> For Loop Example."); for (int i = 0; i < linkedList.size(); i++) { System.out.println(linkedList.get(i)); }
Enhanced for loop
for (String temp : linkedList) { System.out.println(temp); }
While loop
int i = 0; while (i < linkedList.size()) { System.out.println(linkedList.get(i)); i++; }
Iterator
Iterator<String> iterator = linkedList.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); }
collection stream() util (Java 8)
linkedList.forEach((temp) -> { System.out.println(temp); });
One thing should be pointed out is that the running time of For Loop or While Loop is O(n square) because get(i)
operation takes O(n) time(see this for details). The other 3 ways take linear time and performs better.
Linked list is guaranteed to act in sequential order.
From the documentation
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
iterator() Returns an iterator over the elements in this list in proper sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With