Created
October 12, 2022 15:18
-
-
Save rmg007/414ca91ee1eae0c95486fe5dccf69787 to your computer and use it in GitHub Desktop.
iterating over list in java
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.Iterator; | |
| import java.util.List; | |
| import java.util.ListIterator; | |
| public class IteratingOverList { | |
| public static void main(String[] args) { | |
| List<String> list = new ArrayList<>(){{ | |
| add("First"); | |
| add("Second"); | |
| add("Third"); | |
| add("Fourth"); | |
| add("Fifth"); | |
| }}; | |
| // using for loop | |
| for (int i = 0; i < list.size(); i++) { | |
| String element = list.get(i); | |
| System.out.print(element + " "); | |
| } | |
| System.out.println(); | |
| // using enhanced for | |
| for (String element : list) { | |
| System.out.print(element + " "); | |
| } | |
| System.out.println(); | |
| // using iterator | |
| Iterator<String> iterator = list.iterator(); | |
| while (iterator.hasNext()){ | |
| System.out.print(iterator.next()); | |
| } | |
| System.out.println(); | |
| //using listIterator | |
| ListIterator<String> forwardIterator = list.listIterator(); | |
| while (forwardIterator.hasNext()){ | |
| System.out.print(forwardIterator.next()); | |
| } | |
| System.out.println(); | |
| // using listIterator and providing index | |
| ListIterator<String> listIterator = list.listIterator(5); | |
| while (listIterator.hasPrevious()) { | |
| System.out.print(listIterator.previous() + " "); | |
| } | |
| System.out.println(); | |
| // using forEach | |
| list.forEach(e -> System.out.print(e + " ")); | |
| System.out.println(); | |
| // using forEach to strings with more than 5 characters | |
| list.forEach(e-> { | |
| if(e.length() >= 6){ | |
| System.out.print(e + " "); | |
| } | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment