Iterate List Java
By AmarSivas | | Updated : 2021-03-12 | Viewed : 458 times

In the current tutorial, we will see the example of possible ways for list iteration in java.
Table of Contents:
Iterate list java with examples
Here we have shown different types of examples to iterate a list in java.
We had options for
-
1. for
-
2. while
-
3. forEach
-
4. enhanced for
-
5. iterator
-
6. list iterator
-
7. forEach with Stream
In this tutorial for list iteration in java, we will first take the example one list for understanding the ways for list iterate in java.
for loop to iterate list in java
//for loop
System.out.println(">>>>>>>>>>>>>for loop example");
for(int i=0;i<carBrands.size();i++){
System.out.println(carBrands.get(i));
}
while loop to iterate list in java
//while loop
System.out.println(">>>>>>>>>>>>>while loop example");
int i = 0;
while(i<carBrands.size()){
System.out.println(carBrands.get(i));
i++;
}
forEach loop to iterate list in java
//forEach loop
System.out.println(">>>>>>>>>>>>>forEach loop example");
carBrands.forEach(System.out::println);
System.out.println("\n");
enhanced loop to iterate list in java
//enhanced for loop
System.out.println(">>>>>>>>>>>>>enhanced for loop example");
for (String temp : carBrands) {
System.out.println(temp);
}
iterator to iterate list in java
//iterator
System.out.println(">>>>>>>>>>>>>iterator for loop example");
Iterator iterator = carBrands.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
list iterator to iterate list in java
//list iterator
System.out.println(">>>>>>>>>>>>>listIterator for loop example");
ListIterator listIterator = carBrands.listIterator();
while (listIterator.hasNext()){
System.out.println(listIterator.next());
}
foreach with stream to iterate list in java
//foreach with stream
System.out.println(">>>>>>>>>>>>>foreach with stream example");
carBrands.stream().forEach(System.out::println);
To show the entire example with the repository you can refer to Java-iterate-list
Leave A Reply