Program to iterate over a List using Java 8 Lambda

Java 8Object Oriented ProgrammingProgramming

Let us first create a List and add elements −

ArrayList<String>arrayList = new ArrayList<String>();
arrayList.add("100");
arrayList.add("200");
arrayList.add("300");
arrayList.add("400");
arrayList.add("500");

Now, iterate over it with Lambda Expressions −

ArrayList<String>list = arrayList;
System.out.println("Iterating...");
list.stream().forEach(elem -> System.out.println(elem));

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String>arrayList = new ArrayList<String>();
      arrayList.add("100");
      arrayList.add("200");
      arrayList.add("300");
      arrayList.add("400");
      arrayList.add("500");
      arrayList.add("600");
      arrayList.add("700");
      arrayList.add("800");
      arrayList.add("900");
      arrayList.add("1000");
      System.out.println("ArrayList...");
      for (String s: arrayList)
         System.out.println(s);
      ArrayList<String>list = arrayList;
      System.out.println("Iterating...");
      list.stream().forEach(elem -> System.out.println(elem));
   }
}

Output

ArrayList...
100
200
300
400
500
600
700
800
900
1000
Iterating...
100
200
300
400
500
600
700
800
900
1000
raja
Published on 24-Apr-2019 10:37:54
Advertisements