Lambda expressions in Java

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Lambda expressions are most important feature of java 8 which adds functional processing capability to Java and work on Functional programming. Every java developer knows about Object oriented programming that works on the object. Here you do not pass a value but can pass function around but there is no need to go in detail of Functional programming you will use Lambda expressions which will use of functional programming. Other languages such as Scala already have this feature.

Here is the example of Lambda expressions in which you can iterate over a List or any Collection without using any loop in Java. The new Stream class provides a forEach() method, which can be used to loop over all or selected elements of a list. Lambda expressions make the code more readable and coding faster, especially in Collections.

package javatutsworld;
import java.util.ArrayList;
import java.util.List;

public class Java8listTest {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("Apple");
		list.add("Banana");
		list.add("Orange");
		list.add("Grapes");
		
		// prints all elements using Iterable.forEach() method
	      		
		list.forEach(name -> System.out.println(name));
		
		// OR lambda expression with method reference
		
		list.forEach(System.out::println);		
	}
}

Output

Apple
Banana
Orange
Grapes
Apple
Banana
Orange
Grapes
      Advertisements