In this article, we will understand how to iterate over ArrayList using lambda expression. The ArrayList class is a resizable array, which can be found in the java.util package. The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified.
Below is a demonstration of the same −
Suppose our input is −
Run the program
The desired output would be −
The list is defined as: Java Python Scala Mysql Redshift
Algorithm
Step 1 - START Step 2 - Declare namely Step 3 - Define the values. Step 4 - Create an ArrayList, and iterate over it, and display it. Step 5 - In the ArrayList, add elements using the ‘add’ method. Step 6 - Display this on the console. Step 7 - Use the ‘forEach’ loop to iterate over the elements, and display them. Step 8 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.util.ArrayList; public class Demo { public static void print(ArrayList<String> input_list) { System.out.print("\nThe list is defined as:\n "); for(String language : input_list) { System.out.print(language + " "); } } public static void main(String[] args) { System.out.println("The required packages have been imported"); ArrayList<String> input_list = new ArrayList<>(); input_list.add("Java"); input_list.add("Python"); input_list.add("Scala"); input_list.add("Mysql"); input_list.add("Redshift"); print(input_list); } }
Output
The required packages have been imported The list is defined as: Java Python Scala Mysql Redshift
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
import java.util.ArrayList; public class Demo { public static void print(ArrayList<Integer> input_list) { System.out.print("\nThe list is defined as:\n "); for(Integer elements : input_list) { System.out.print(elements + " "); } } public static void main(String[] args) { System.out.println("The required packages have been imported"); ArrayList<Integer> input_list = new ArrayList<>(); input_list.add(500); input_list.add(600); input_list.add(700); input_list.add(800); input_list.add(950); print(input_list); } }
Output
The required packages have been imported The list is defined as: 500 600 700 800 950