I started my new year by setting up Java 8 in my machine and playing with Lambda Expressions. Lambda expressions have been my favorite feature in C#. You can refer to some of my posts on Lambda expressions here.
Instead of adding more words to the never-ending information on Lambda expressions on the web let’s understand it with an example.
Let’s create an interface called Greetings with just one method like this.
interface Greetings{ void print(String message); }
If you want to create an instance of Greetings and invoke the print() method here’s the old way of doing things.
Greetings oldGreetings = new Greetings(){ public void print(String message){ System.out.println("Old greetings: " + message); } }; oldGreetings.print("Welcome 2014");
The output of this code is Old greetings: Welcome 2014. Now, you don’t want to be creating an anonymous inner class for this. Bring in Lambda expressions as shown here.
Greetings newGreetings = message -> System.out.println("New greetings: " + message); newGreetings.print("Welcome 2014");
It cannot get simpler than this. Notice the use of -> in the code. newGreetings is a reference to a dynamically generated anonymous inner class object. When I try to print the class name of newGreetings it gives me Hello2014$$Lambda$1/518248. In other words newGreetings is an instance of what is called a Functional interface in Java 8. Hello2014 is the class with a main method where I created newGreetings. Here’s the complete code.
interface Greetings{ void print(String message); } public class Hello2014{ public static void main(String[] args){ Greetings oldGreetings = new Greetings(){ public void print(String message){ System.out.println("Old greetings: " + message); } }; oldGreetings.print("Welcome 2014"); Greetings newGreetings = message -> System.out.println("New greetings: " + message); newGreetings.print("Welcome 2014"); System.out.println(newGreetings.getClass().getName()); } }