List Iteration using Lambda Expression in Java 8

Lambda Expression:
Lambda expressions are introduced in Java 8 and I feel its a great feature. Here we are going to see how to iterate the array list using Lambda expression.

list iteration using lambda

 

List Iteration using Lambda Expression:

[java]
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

public class LambdaIteration{
public static void main(String[] args){
List<String> progLangLst = new ArrayList<String>();
progLangLst.add("C");
progLangLst.add("C++");
progLangLst.add("Java");
progLangLst.add("PHP");
progLangLst.add(".Net");

// old way [from java 1.5]
System.out.println("Printing the list values – old way");
for(String progLang : progLangLst){
System.out.println(progLang);
}

// Using Lambda expressions – new way [only in java 8]
// Iterating and printing the progLangLst using Lambda expression
System.out.println("\nPrinting the list values using Lambda Expression");
progLangLst.forEach((String progLang) -> System.out.println(progLang));

// Method calling in Lambda Iteration
System.out.println("\nPrinting the list values using Lambda Expression with method call");
LambdaIteration lambda = new LambdaIteration();
progLangLst.forEach((String progLang) -> System.out.println(lambda.printLang(progLang)));

// Even without the datatype we can print the values
System.out.println("\nPrinting the list values using Lambda Expression without the datatype");
progLangLst.forEach((progLang) -> System.out.println(progLang));

}

public String printLang(String progLang){
return progLang;
}
}
[/java]

 

 

Output:

[plain]
Printing the list values – old way
C
C++
Java
PHP
.Net

Printing the list values using Lambda Expression
C
C++
Java
PHP
.Net

Printing the list values using Lambda Expression with method call
C
C++
Java
PHP
.Net

Printing the list values using Lambda Expression without the datatype
C
C++
Java
PHP
.Net
[/plain]

Hope the above inline comments helped you to understand it. Still need any clarifications please post your comments/feedbacks in comments section.

 

 

Java Recommended Books:

Leave a Reply