Iterate a list in Java : in this Post we will discover different ways to browse a list in Java. (ArrayList)

List.toString()

If we want to iterate over a list in java , we can do that by converting the list to a string using the toString() function, then outputting it

import java.util.*;

public class Main
{
  public static void main (String[] args)
  {
     List<String> cars= new ArrayList<String>();
     color.add("Bmw");
     color.add("Peugeot");
     color.add("Volkswagen");

     System.out.println(cars.toString());
  }
}

Output :


Bmw
Peugeot
Volkswagen

Using For loop

import java.util.*;

public class Main
{
  public static void main (String[] args)
  {
    List<String> cars= Arrays.asList("Bmw", "Peugeot", "Volkswagen");

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

Output :

Bmw
Peugeot
Volkswagen

Using the for-each loop

import java.util.*;

public class Main
{
  public static void main (String[] args)
  {
    List<String> cars= Arrays.asList("Bmw", "Peugeot", "Volkswagen");

    for (String str : cars) {
      System.out.println(str);
    }
  }
}

Output :

Bmw
Peugeot
Volkswagen

Using Iterator

Iterator is an interface that belongs to the “collection” framework. It allows us to browse a collection using the following methods :

  • hasNext() : returns true if Iterator has more items to iterate.
  • next() : it returns the next element in the collection until the hasNext() method returns true. This method throws the ‘NoSuchElementException‘ exception if there is no more element.
import java.util.*;

public class Main
{
  public static void main (String[] args)
  {
    List<String> cars= Arrays.asList("Bmw", "Peugeot", "Volkswagen");

    Iterator<String> i = cars.iterator();
    while (i.hasNext()) {
      System.out.println(i.next());
    }
  }
}

Output :

Bmw
Peugeot
Volkswagen

References :

Tagged:

Laisser un commentaire