Java 8 Lambda Expression Using Simple Example
In this post we will understand the Java 8 Lambda expression using a simple example.
Before Java 8 everything was mostly object oriented. Except primitives everything in java existed as objects
All calls to methods/functions are to be made using objects or class references.
Methods/Functions did not exist independently by itself.
With Java 8, functional programming has been introduced. So we can make use of anonymous functions.
So what is Lambda expression?
Lambda Expression can be defined as an Anonymous Function that allows users to pass methods as arguments. This helps removes a lot of boilerplate code. Lambda Functions have no access modifiers(private, public or protected), no return type declaration and no name.Lambda expressions let users pass "functions" to code. So we can write code more easily that we used to need a whole mess
of interfaces/abstract classes for. For example, suppose we have code that has some complex loop/conditional logic or workflow.
At one step we want to do something different. With lambda expressions, we can just pass in that "something different."
Syntax-
(arg1, arg2, arg3,...) -> { body }
Lets Begin-
Consider the following interface Greetings having a single method sayHello-package com.javainuse; public interface Greetings { public void sayHello(String name); }
The Greeting interface method sayHello can be implemented in 3 ways as below-
-
Traditional Java Class implementing the interface-
package com.javainuse; public class JavaTraditionalClass implements Greetings { @Override public void sayHello(String name) { System.out.println("Hello World " + name); } public static void main(String[] args) { JavaTraditionalClass test = new JavaTraditionalClass(); greet(test, "Tom"); } private static void greet(Greetings greetingsInstance, String name) { greetingsInstance.sayHello(name); } }
-
Using Java Anonymous class-
package com.javainuse; public class JavaAnonymousClass { public static void main(String[] args) { Greetings greetingsInstance = new Greetings() { @Override public void sayHello(String name) { System.out.println("Hello World " + name); } }; greet(greetingsInstance, "Tom"); } private static void greet(Greetings greetingsInstance, String name) { greetingsInstance.sayHello(name); } }
-
Using Java Lambda Function-
package com.javainuse; public class JavaLambda { public static void main(String[] args) { Greetings greetingsInstance=n -> System.out.println("Hello World " + n); greet(greetingsInstance, "Tom"); } private static void greet(Greetings greetingsInstance, String name) { greetingsInstance.sayHello(name); } }
The Lambda code syntax used above is
n -> System.out.println("Hello World " + n);
- The element to the left of the arrow(->) are the parameters of the lambda. In this case the input parameter is defined as- n. It can have receive zero, one or more parameters. i.e ( ) -> { perform function } or (n)-> { perform function } or (m,n )-> { perform function } and so on.
- To the right of the arrow(->) we have the lambda body. This is where the actual logic is written. The logic for the above lambda function is to print the message along with the passed parameter.
Regarding Structure of Lambda functions
- @FunctionalInterface is a new interface added in Java 8 .
It indicates that the interface is to be used as a functional interface.package com.javainuse; @FunctionalInterface public interface Greetings { public void sayHello(String name); }
This annotation is optional. Even if not annotated with @FunctionalInterface, an interface can still be used as a functional interface. -
The interface for which we are writing the lambda function should have only a single method.
if more than one method is specified for an interface annotated with
we get a compiler exception
Invalid '@FunctionalInterface' annotation; Greetings is not a functional interface
Advantages of Lambda functions
-
Until Java 8 lists and sets were typically processed by
client code obtaining an iterator from the collection, then using that to iterate over its elements and
process each in turn. If the processing of different elements is to proceed in parallel, it was the
responsibility of the client code, not the collection, to organise this.
Java 8 makes it easier to distribute processing of collections over multiple threads.
Collections can now organise their own iteration internally, transferring responsibility for parallelisation from client code into library code. -
Fewer lines of code. As explained above the user has to only declare what is to be done in a declarative way.
n -> System.out.println("Hello World " + n);
So user has to type reduced amount of code. - Using Java 8 Lambda expressions higher efficiency can be achieved. Using CPUs with multicores, user can take advantage of the multicore CPUs by parallel processing of collections using lambda.
Download Source Code
Download it - Java 8 Lambda Expression Simple ExampleSee Also
Java - PermGen space vs MetaSpace Understand Java 8 Method References using Simple Example Java 8-Internal vs. External Iteration. Understanding Java 8 Streams using examples. Understanding Java 8 Optional using examples.