Daur Ulang liwat Java Loop

Ing tutorial iki, kita bakal nemokake limang cara sing beda kanggo mbukak liwat ArrayList ing Java. Ing Java 8, kita bisa nggunakake metode forEach uga kelas iterator kanggo nggulung ArrayList.



Looping liwat ArrayList

Utamane ana 5 macem-macem cara kanggo ngubengi ArrayList

  1. Klasik Kanggo Loop
  2. Majeng Kanggo Loop
  3. Iterator
  4. Nalika Loop
  5. ForEach (Jawa 8)

Kaping pisanan, ayo nggawe ArrayList kanggo digunakake ing conto loop:


import java.util.ArrayList; import java.util.List; public class LoopOverArrayExamples {
private List fruitBasket = new ArrayList(0);
public void addFruitsToBasket() {
fruitBasket.add('Apple');
fruitBasket.add('Banana');
fruitBasket.add('Pear');
fruitBasket.add('Mango');
} }

Gegandhengan:

Nggunakake Klasik Kanggo Loop

for (int i=0; iSystem.out.println(fruitBasket.get(i)); }

Majeng Kanggo Loop

for(String fruit : fruitBasket) {
System.out.println(fruit); }

Nggunakake Iterator

Iterator fruitIterator = fruitBasket.iterator(); while (fruitIterator.hasNext()) {
System.out.println(fruitIterator.next()); }

Nggunakake Nalika Loop

int i = 0; while (i < fruitBasket.size()) {
System.out.println(fruitBasket.get(i));
i++; }

ForEach (Jawa 8)

fruitBasket.forEach( (fruit) ->
System.out.println(fruit) );