To iterate over the elements in an ArrayList
in Java, you can use the for-each
loop or the forEach()
method.
Here's an example of how to use the for-each
loop to iterate over an ArrayList
:
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); // Iterate over the elements in the list and print each element to the console for (String element : list) { System.out.println(element); } } }
This code creates an ArrayList
of strings and then uses the for-each
loop to iterate over the elements in the list. The loop variable element
is automatically set to the value of each element in the list, and the loop continues until it has processed all the elements.
You can use a similar approach to iterate over an ArrayList
of any type of data.
Alternatively, you can use the forEach()
method of the ArrayList
class, which allows you to specify a Consumer
object that performs an action on each element in the list:
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); // Iterate over the elements in the list and print each element to the console list.forEach(e -> System.out.println(e)); } }
This code uses the forEach()
method to iterate over the elements in the ArrayList
and prints each element to the console. The forEach()
method takes a Consumer
object as an argument.