Iterate Over a List in Java - Six different ways
In this section, we will show 6 different ways to iterate through a List in Java.
- Using For Loop
- Using doWhile
- Using Advanced For Loop
- Using Iterator
- Using While Loop
- Using Java 8 forEach
1. Using For Loop
// create list
List<String> languages = new ArrayList<String>();
// add 5 different values to list
languages.add("Java");
languages.add("Kotlin");
languages.add("Scala");
languages.add("Python");
languages.add("Go");
// iterate via "for loop"
System.out.println("==> For Loop Example.");
for (int i = 0; i < languages.size(); i++) {
System.out.println(languages.get(i));
}
2. Using doWhile
// create list
List<String> languages = new ArrayList<String>();
// add 5 different values to list
languages.add("Java");
languages.add("Kotlin");
languages.add("Scala");
languages.add("Python");
languages.add("Go");
// iterate via "do while loop"
System.out.println("\n==> doWhile Loop Example....");
int j = 0;
do {
System.out.println(languages.get(j));
j++;
} while (j < languages.size());
3. Using Advanced For Loop
// create list
List<String> languages = new ArrayList<String>();
// add 5 different values to list
languages.add("Java");
languages.add("Kotlin");
languages.add("Scala");
languages.add("Python");
languages.add("Go");
// iterate via Advanced for loop
System.out.println("\n==> Advance For Loop Example..");
for (String temp : languages) {
System.out.println(temp);
}
4. Using Iterator
// create list
List<String> languages = new ArrayList<String>();
// add 5 different values to list
languages.add("Java");
languages.add("Kotlin");
languages.add("Scala");
languages.add("Python");
languages.add("Go");
// iterate via "iterator loop"
System.out.println("\n==> Iterator Example...");
Iterator<String> iterator = languages.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
5. Using While Loop
// create list
List<String> languages = new ArrayList<String>();
// add 5 different values to list
languages.add("Java");
languages.add("Kotlin");
languages.add("Scala");
languages.add("Python");
languages.add("Go");
// iterate via "while loop"
System.out.println("\n==> While Loop Example....");
int i = 0;
while (i < languages.size()) {
System.out.println(languages.get(i));
i++;
}
6. Java 8 forEach
// create list
List<String> languages = new ArrayList<String>();
// add 5 different values to list
languages.add("Java");
languages.add("Kotlin");
languages.add("Scala");
languages.add("Python");
languages.add("Go");
// From Java 8:forEach
System.out.println("\n==> collection stream() util....");
languages.forEach((temp) -> {
System.out.println(temp);
});
More Interesting topics,