How to display all the elements in ArrayList in Java using loop
We can display all the elements in ArrayList in Java using :
- By use of for loop
- By use of enhanced for loop
- By use of lambda expression
- By use of method reference
- By use of stream
Let’s see in example:
- import java.util.ArrayList;
- import java.util.Arrays;
- public class MainClass
- {
- public static void main(String[] arg)
- {
- ArrayList list = new ArrayList(Arrays.asList(1,2,3,4,5));
- // Display all the elements in ArrayList in Java using for loop?
- System.out.println("By use of for loop");
- for(int i = 0; i < list.size(); i++)
- {
- System.out.println(list.get(i));
- }
- // Display all the elements in ArrayList in Java using enhanced for loop?
- System.out.println("By use of enhanced for loop");
- for(Integer ele : list)
- {
- System.out.println(ele);
- }
- // Display all the elements in ArrayList in Java using forEach loop
- // Using lambda expression
- System.out.println("By use of lambda expression");
- list.forEach(a -> System.out.println(a));
- // Display all the elements in ArrayList in Java using forEach loop
- // Using method reference
- System.out.println("By use of method reference");
- list.forEach(System.out::println);
- // Display all the elements in ArrayList in Java using forEach loop with Streams
- System.out.println("By use of stream");
- list.stream().forEach(ele -> System.out.println(ele));
- }
- }
Articoli simili
- How to make a to-do-list using PHP and connecting it using MySQL
- Come si aggiungono più tipi di oggetti a un arrayList?
- Come aggiungere un elemento a un arraylist che si trova in una hashmap
- Quale disco rigido esterno è meglio, Seagate o WD Elements, e perché? Puoi condividere la tua esperienza se li hai usati?