Created
October 11, 2022 14:43
-
-
Save rmg007/e33e95e12947a7cb6592d2d13bdbd033 to your computer and use it in GitHub Desktop.
Traversing elements in the collection interface
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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