I did further research into Lambda expressions in Java 8 after my last article.
It was then that I came to know about “Functional Interfaces”. Understanding the basics is the key to learning Lambda expressions in Java 8.
A Functional Interface is an interface that has only one abstract method. Lambdas help us get rid of boilerplate code and remove use of anonymous inner classes.
See below for examples with a custom interface and see how code with and without lambda expressions look.
Lets see the how this lambda expression really works.
(name, age) -> System.out.println("Hello " + name + ", you are " + age + " old");
UserInfo has only one method
printInfo(String name, Integer age). This is all information for the compiler to create an anonymous inner class. This expression has two parts separated by a
-> operator. The first part,
(name, age) represents the parameter list for the method and the code after
-> is the body for the method.
userInfo is a function that can be invoked by passing parameters
Predicate is a Functional Interface included in Java 8 which represents a boolean valued function. It has a
boolean test(T t) method which accepts an object as parameter and returns a boolean result. Check the below example and see if you are able to figure how it works
Using lambda expressions is performance and memory efficient than using Anonymous inner classes. When we create an anonymnous inner class, JVM has to create a new object, allocate memory, initialize static blocks, run the constructor methods etc. These are not required when creating a lambda expression.