Explain the difference between the Iterator interface and the forEach method in Java's Stream API.
sobes.tech AI
Answer from AI
The Iterator interface in Java provides a way to sequentially traverse elements of a collection with explicit control over the loop, for example, using the hasNext() and next() methods. It allows manual iteration over elements and also the removal of elements during iteration.
The forEach method in the Stream API is a more declarative way to process stream elements. It accepts a lambda expression or method reference and applies it to each element, hiding the iteration details. forEach does not allow modifying the collection's structure during traversal and is typically used for side effects.
Example:
List<String> list = Arrays.asList("a", "b", "c");
// Using Iterator
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
// Using forEach
list.stream().forEach(element -> System.out.println(element));
The main difference is that Iterator gives full control over the traversal process, including the ability to remove elements, while forEach provides a more convenient and concise way to apply an operation to each element without managing iteration.