linkedlist iterator
Fri Jun 07 2024 12:22:52 GMT+0000 (Coordinated Universal Time)
Saved by
@dbms
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);
}
}
}
content_copyCOPY
Comments