Input/Output and Streams in Java
Alex Liu
Software Development Engineer
import java.util.ArrayList;
public class SampleData {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
}
}
[Alice, Bob, Charlie]
// Import ListIterator class import java.util.ListIterator;
// Create ListIterator object for sample list `names` ListIterator<String> it = names.listIterator(); // Use .hasNext() and `.next()` to iterate the list and print line by line while (it.hasNext()) { System.out.println(it.next()); }
Alice
Bob
Charlie
.previous()
to move backward in the list// Create ListIterator object for sample list `names`
ListIterator<String> it = names.listIterator(names.size());
// Use .hasPrevious() to check if the iterator reach the beginning of the list
while (it.hasPrevious()) {
// Use .previous() to retrieve the element in reverse order
System.out.println(it.previous());}
Charlie
Bob
Alice
.set()
method// Create ListIterator object for sample list names ListIterator<String> it = names.listIterator();
// Iterate the list and modify element using .set() while (it.hasNext()) { String name = it.next(); if ("Bob".equals(name)) it.set("Bobby"); }
names
list:[Alice, Bobby, Charlie]
.add()
to add elementsListIterator<String> it = names.listIterator();
// Iterate the list and insert element using .add() while (it.hasNext()) { String name = it.next(); if ("Charlie".equals(name)) it.add("David"); }
names
list:[Alice, Bobby, Charlie, David]
ListIterator
extends Iterator
Key Methods Recap
.next()
/.previous()
: Navigate forward and backward.set()
: Modify the current element.add()
: Insert elements dynamically.remove()
: Safely delete elementsArrayList
, LinkedList
, etc.)Input/Output and Streams in Java