There are different ways to print a List, below are some example to print a list using:
1. For loop
2. While loop, and
3. Iterator
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class printmyList {
public static void main(String[] args) {
String myArray[] = new String[] { "John", "Bob", "Tom", "Mick" };
// convert array to list
List<String> myList = Arrays.asList(myArray);
// for loop
System.out.println("Using for loop..");
for (int i = 0; i < myList.size(); i++) {
System.out.println(myList.get(i));
}
// while loop
System.out.println("Using while loop..");
int j = 0;
while (j < myList.size()) {
System.out.println(myList.get(j));
j++;
}
// iterator loop
System.out.println("Using Iterator..");
Iterator<String> iterator = myList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
0 Comment(s)