Java Program to Iterate over ArrayList using Lambda Expression

JavaCampus InterviewServer Side ProgrammingProgramming

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 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");
      System.out.print("\nThe list is defined as: ");
      input_list.forEach((e) -> {
         System.out.print(e + " ");
      });
   }
}

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 {
   static void print(ArrayList<String> input_list){
      System.out.print("\nThe list is defined as: ");
      input_list.forEach((e) -> {
         System.out.print(e + " ");
      });
   }
   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
raja
Updated on 30-Mar-2022 11:51:45

Advertisements