Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - iterating a linked list

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?

like image 454
tomermes Avatar asked Jan 22 '11 11:01

tomermes


People also ask

Can you iterate through a linked list Java?

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.

How do you make a linked list iterator in Java?

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.


2 Answers

I found 5 main ways to iterate over a Linked List in Java (including the Java 8 way):

  1. For Loop
  2. Enhanced For Loop
  3. While Loop
  4. Iterator
  5. Collections’s stream() util (Java8)

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.

like image 112
Gherbi Hicham Avatar answered Sep 26 '22 07:09

Gherbi Hicham


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.

like image 32
Dave G Avatar answered Sep 24 '22 07:09

Dave G