Comment boucler / itérer une liste en Java
Ici, je vous montre quatre façons de boucler une liste en Java.
-
Boucle d'itérateur
-
Pour boucle
-
Boucle For (Adcance)
-
Boucle while
package com.example.core;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class ArrayToList {
public static void main(String[] argv) {
String sArray[] = new String[] { "Array 1", "Array 2", "Array 3" };
// convert array to list
List lList = Arrays.asList(sArray);
// iterator loop
System.out.println("#1 iterator");
Iterator iterator = lList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// for loop
System.out.println("#2 for");
for (int i = 0; i < lList.size(); i++) {
System.out.println(lList.get(i));
}
// for loop advance
System.out.println("#3 for advance");
for (String temp : lList) {
System.out.println(temp);
}
// while loop
System.out.println("#4 while");
int j = 0;
while (j < lList.size()) {
System.out.println(lList.get(j));
j++;
}
}
}
Sortie
#1 iterator Array 1 Array 2 Array 3 #2 for Array 1 Array 2 Array 3 #3 for advance Array 1 Array 2 Array 3 #4 while Array 1 Array 2 Array 3