Iterating over ArrayLists in Java

Prerequisite : ArrayList in Java

Method 1 : Using for loop :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java  program to iterate over an ArrayList
// using for loop
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
  
        // initializing ArrayList
        List<Integer> numbers = Arrays.asList(1, 2, 3,
                                       4, 5, 6, 7, 8);
  
        // For Loop for iterating ArrayList
        for (int i = 0; i < numbers.size(); i++) 
            System.out.print(numbers.get(i) + " ");        
    }
}

chevron_right


Output:

1 2 3 4 5 6 7 8

Method 2: Using for each loop

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to iterate
// over an arraylist using for Each loop
import java.util.*;
class GFG {
  
    public static void main(String[] args)
    {
        // initializing ArrayList
        List<Integer> numbers = Arrays.asList(1, 2, 3,
                                      4, 5, 6, 7, 8);
  
        // For Each Loop for iterating ArrayList
        for (Integer i : numbers)
            System.out.print(i + " ");
    }
}

chevron_right


Output:

1 2 3 4 5 6 7 8

Method 3 : Using Iterator

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to iterate over an arraylist
// using Iterator
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        // initializing ArrayList
        List<Integer> numbers = Arrays.asList(1, 2, 3
                                       4, 5, 6, 7, 8);
  
        // Looping ArrayList using Iterator
        Iterator it = numbers.iterator();
        while (it.hasNext())
            System.out.print(it.next() + " ");
    }
}

chevron_right


Output:

1 2 3 4 5 6 7 8

Method 3 : Using For Each Method of Java 8

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to iterate over an arraylist
// using Iterator
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        // initializing ArrayList
        List<Integer> numbers = Arrays.asList(1, 2, 3
                                       4, 5, 6, 7, 8);
  
           //lambda
        numbers.forEach(number->System.out.println(number));
  
    }
}

chevron_right


Output:

1 2 3 4 5 6 7 8

This article is contributed by Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : SandeepChaudhary



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.