QNA > H > How To Display All The Elements In Arraylist In Java Using Loop

How to display all the elements in ArrayList in Java using loop

We can display all the elements in ArrayList in Java using :

  1. By use of for loop
  2. By use of enhanced for loop
  3. By use of lambda expression
  4. By use of method reference
  5. By use of stream

Let’s see in example:

  1. import java.util.ArrayList; 
  2. import java.util.Arrays; 
  3.  
  4. public class MainClass  
  5. public static void main(String[] arg)  
  6. ArrayList list = new ArrayList(Arrays.asList(1,2,3,4,5)); 
  7.  
  8. // Display all the elements in ArrayList in Java using for loop? 
  9. System.out.println("By use of for loop"); 
  10. for(int i = 0; i < list.size(); i++) 
  11. System.out.println(list.get(i)); 
  12.  
  13. // Display all the elements in ArrayList in Java using enhanced for loop? 
  14. System.out.println("By use of enhanced for loop"); 
  15. for(Integer ele : list) 
  16. System.out.println(ele); 
  17.  
  18. // Display all the elements in ArrayList in Java using forEach loop 
  19. // Using lambda expression  
  20. System.out.println("By use of lambda expression"); 
  21. list.forEach(a -> System.out.println(a)); 
  22.  
  23. // Display all the elements in ArrayList in Java using forEach loop 
  24. // Using method reference 
  25. System.out.println("By use of method reference"); 
  26. list.forEach(System.out::println); 
  27.  
  28. // Display all the elements in ArrayList in Java using forEach loop with Streams 
  29. System.out.println("By use of stream"); 
  30. list.stream().forEach(ele -> System.out.println(ele)); 
  31.  

Di Yeargain

Come registrare su Nintendo Switch più di 30 secondi senza una scheda di acquisizione :: Esiste un sistema operativo migliore di iOS e Android?
Link utili