Skip to content

Instantly share code, notes, and snippets.

@rmg007
Created October 11, 2022 14:43
Show Gist options
  • Select an option

  • Save rmg007/e33e95e12947a7cb6592d2d13bdbd033 to your computer and use it in GitHub Desktop.

Select an option

Save rmg007/e33e95e12947a7cb6592d2d13bdbd033 to your computer and use it in GitHub Desktop.
Traversing elements in the collection interface
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class CollectionInterfaceTraversalMethods {
public static void main(String[] args) {
Collection<Integer> collection1 = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
// 1- using the iterator method
Iterator<Integer> iterator = collection1.iterator();
while (iterator.hasNext()) {
Integer currValue = iterator.next();
System.out.print(currValue);
// you can remove elements using iterator
// iterator.remove();
}
System.out.println();
// 2- for each method
for (int n : collection1) {
System.out.print(n);
// you can't remove elements inside for each method
// this will throw an exception
// collection1.remove(n);
}
System.out.println();
// 3- iterate and perform an action
collection1.forEach(System.out::print);
System.out.println();
// another example to print even numbers:
collection1.forEach(e -> {
if (e % 2 == 0) {
System.out.print(e);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment