Java - LinkedList Methods Part 4: Iterating Over Elements
Iteration allows traversal of all elements using loops or iterators.
Examples and Explanation
Using a for-each Loop
for (String item : list) {
System.out.print(item + " ");
}
// Output: Apple Date Fig
Explanation: The simplest way to iterate over all elements in a LinkedList.
Using an Iterator
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Explanation: Provides more control during iteration, such as removing elements while iterating.
Using a for Loop with Index
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
Explanation: Useful when index-based operations are needed during traversal.
Using a Stream
list.stream().forEach(System.out::println);
Explanation: Leverages Java streams for concise and functional-style iteration.