import java.util.LinkedList; import java.util.Iterator; public class LinkedListIteratorExample { public static void main(String[] args) { // Create a LinkedList and add some fruit names LinkedList<String> fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Obtain an iterator for the LinkedList Iterator<String> iterator = fruits.iterator(); // Use the iterator to traverse through the LinkedList System.out.println("Using Iterator to traverse through the LinkedList:"); while (iterator.hasNext()) { String fruit = iterator.next(); System.out.println(fruit); } // Use a for-each loop to traverse through the LinkedList System.out.println("\nUsing for-each loop to traverse through the LinkedList:"); for (String fruit : fruits) { System.out.println(fruit); } // Obtain a new iterator for the LinkedList iterator = fruits.iterator(); // Reset the iterator while (iterator.hasNext()) { String fruit = iterator.next(); if (fruit.startsWith("B")) { iterator.remove(); // Remove elements that start with "B" } } // Display the LinkedList after removal of elements that start with 'B' System.out.println("\nLinkedList after removal of elements that start with 'B':"); for (String fruit : fruits) { System.out.println(fruit); } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter