Java 8 Lambda Expression with examples

Java 8 Lambda is one of the most awaited features the java community was waiting for. Inclusion of lambda to th is a first step to introduce functional programming in hard core OOPs framework.

What is Lambda

A lambda expression is a block of code that you can pass around so it can be executed later, just once or multiple times. It is a block of code with or without parameters.

How to use lambda?

The main intention of using lambda is to pass a block of code. The code block can be used of immediate execution or can be later too. But Java is object oriented programming and until now creation of any block had to be done by wrapping around the class and creating an object. Lets look at some of the regular java examples:

In the above example, Arrays.sort method receives a block of code (lambda), as a second argument which is wrapped around an object of some class which implements Comparator<String> interface. The block is executed when compare method is invoked

Method References

Sometimes, there is already a method that carries out exactly the action that you'd like to pass on to some other code. For example, you want to pass the String method equalsIgnoreCase to Arrays.sort method: