JAVA-Six (6) ways to Iterate through Java List

There are 6 ways you can iterate through List.


  • For Loop
  • doWhile
  • Advanced For Loop
  • Iterator
  • While Loop
  • Collections’s stream() util (Java8)


Java Example:



package com.knowledgefactory;




import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;



/**

 * @author www.knowledgefactory.net

 */


public class KnowledgeFactoryIterateThroughList {

public static void main(String[] argv) {

// create list
List<String> knowledgefactorylist = new ArrayList<String>();

// add 5 different values to list
knowledgefactorylist.add("Java");
knowledgefactorylist.add("Kotlin");
knowledgefactorylist.add("Scala");
knowledgefactorylist.add("Python");
knowledgefactorylist.add("Go");

// iterate via Advanced for loop
System.out.println("\n==> Advance For Loop Example..");
for (String temp : knowledgefactorylist) {
System.out.println(temp);
}

// iterate via "iterator loop"
System.out.println("\n==> Iterator Example...");
Iterator<String> knowledgefactoryIterator = knowledgefactorylist.iterator();
while (knowledgefactoryIterator.hasNext()) {
System.out.println(knowledgefactoryIterator.next());
}
// iterate via "for loop"
System.out.println("==> For Loop Example.");
for (int i = 0; i < knowledgefactorylist.size(); i++) {
System.out.println(knowledgefactorylist.get(i));
}

// iterate via "do while loop"
System.out.println("\n==> doWhile Loop Example....");
int j = 0;
do {
System.out.println(knowledgefactorylist.get(j));
j++;
} while (j < knowledgefactorylist.size());

// iterate via "while loop"
System.out.println("\n==> While Loop Example....");
int i = 0;
while (i < knowledgefactorylist.size()) {
System.out.println(knowledgefactorylist.get(i));
i++;
}

// From Java 8:collection stream() util
System.out.println("\n==> collection stream() util....");
knowledgefactorylist.forEach((temp) -> {
System.out.println(temp);
});
}
}


Output:



==> Advance For Loop Example..
Java
Kotlin
Scala
Python
Go

==> Iterator Example...

Java
Kotlin
Scala
Python
Go
==> For Loop Example.
Java
Kotlin
Scala
Python
Go

==> doWhile Loop Example....

Java
Kotlin
Scala
Python
Go

==> While Loop Example....

Java
Kotlin
Scala
Python
Go

==> collection stream() util....

Java
Kotlin
Scala
Python
Go


This article is contributed by Sibin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Comments