Java 8 – Lambda Expressions

November 14, 2018 Off By ravi24kant

In this post, I’ll cover lambda expression Java and ideas around it in 3 parts. Below is out arrange to act.

  1. What’s a lambda expression in Java?
  2. Java 8 functional interface
  3. Lambda expression examples

Let’s continue the setup and move step by step.

What’s a lambda expression in Java?

In programming, a Lambda function is simply AN anonymous function, i.e., a function with no name and while not being finite to an identifier.

In alternative words, lambda expressions Java are unnamed functions given as constant values, and written precisely within the place wherever it’s required, generally as a parameter to another function.
The most necessary options of Lambda Expressions is that they execute within the context of their look. So, the same lambda expression is executed differently in another context (i.e. logic are going to be the same however results are completely different supported different parameters passed to function).

Whatever we discussed above is full of keywords and difficult to understand if you do not have deep understanding of what’s lambda expression. So, once you read the full article, I suggest you to re-read above paragraph once agian.

So, it’s clear that lambda is a few quite function without name and identifiers. Well, that’s a huge deal? Why most are therefore excited?

The answer lies within the edges involved in functional programming over object adjusted programming (OOP). Most OOP languages evolve around objects and instances and treat solely them their first-class voters. Another necessary entity i.e. functions take back seat. this can be especially true in Java, wherever functions can’t exist outside AN object. A function itself doesn’t mean something in java, till it’s associated with some object or instance.

But in functional programming, you’ll be able to define functions, provide them reference variables and pass them as method arguments and far a lot of. JavaScript may be an example of this wherever you’ll be able to pass callback methods e.g. to ajax calls. It’s terribly helpful feature and has been lacking in java from starting. now with Java 8, we will additionally use these lambda expressions.

Lambda Expression Java Syntax

A typical Java 8 lambda expression syntax is like this:

(x, y) -> x + y //This perform takes 2 parameters and return their total.

Now supported a type of x and y, the method is also utilized in multiple places. Parameters will match to int, or integer or just String also. supported context, it’ll either add 2 integers or concat 2 strings.

Syntax:

The other doable syntax’s of  lambda expression are:

(parameters) -> expression //1

or

(parameters) -> //2

or

() -> expression

2. Java Lambda Expressions examples

Let’s see some samples of Java lambda expressions as well:

(int a, int b) -> a * b // takes 2 integers and returns their multiplication

(a, b) -> a - b // takes 2 numbers and returns their difference

() -> 99 // takes no values and returns 99

(String a) -> System.out.println(a) // takes a string, prints its worth to the console, and returns nothing

a -> 2 * a // takes a number and returns the results of doubling it

c -> {complicated statements } // takes a set and do some processing

Options of Java Lambda Expressions

Let’s determine some options of the lambda expression:

A lambda expression will have zero, one or a lot of parameters. The type of the parameters is expressly declared or it is inferred from the context. Multiple parameters are boxed in necessary parentheses and separated by commas. Empty parentheses are used to represent AN empty set of parameters. When there’s one parameter, if its type is inferred, it’s not obligatory to use parentheses. e.g. a -> return a*a.

The body of the lambda expressions will contain zero, one or additional statements. If the body of lambda expression has single statement curly brackets are not obligatory and also the return kind of the anonymous function is that the same as that of the body expression. once there’s over one statement in body than these should be closed in curly brackets.

So, we tend to get a short summary of what is the lambda expression. Please have patience if you’re feeling lost and not capable to relate, however, it is used in java programming language. we are going to work out everything. therefore let’s get going.

Before going deep in a relation between lambda expressions and java programming, you need to understand functional interfaces moreover. it’s simply too necessary.

2. Java 8 functional interface

Single Abstract method interfaces (SAM Interfaces) isn’t a brand new concept. It means that interfaces with only 1 single method. In Java, we tend to have already got several samples of such guided missile interfaces. From Java 8, they’ll even be referred to as functional interfaces also. Java 8, enforces the rule of single responsibility by marking these interfaces with a replacement annotation i.e. @FunctionalInterface.

For example, a new definition of the Runnable interface is like this:

@FunctionalInterface
public interface Runnable

If you are trying to feature a brand new method in any functional interface, the compiler wouldn’t permit you to try and do this and can throw compile time error.

So far therefore smart. But, however, they’re related to Lambda expressions? Let’s determine the solution.

We know that Lambda expressions are anonymous functions with no name and they are passed (mostly) to alternative functions as parameters. Well, in java method parameters forever have a type and this type info is searched for to see that method must be known as just in case of method overloading or perhaps easy method calling. So, primarily each lambda expression additionally should be convertible to some sort to be accepted as method parameters. Well, that kind within which lambda expressions are reborn, are always of a functional interface type.

Let’s realize it with AN example. If we’ve to write down a thread which can print “useLamdaExpression” in a console then the simplest code will be:

new Thread(new Runnable(){
@Override
public void run() {
   System.out.println("useLamdaExpression");
}
}).start();
If we tend to use the lambda expression for this task then the code is:
new Thread(() -> {
                   System.out.println("useLamdaExpression");
                 }).start();

We have additionally seen that Runnable is AN functional interface with single method run(). So, after you pass a lambda expression to the creator of Thread class, the compiler tries to convert the expression into equivalent Runnable code as shown in the 1st code sample. If compiler succeeds then everything runs fine, if the compiler isn’t able to convert the expression into equivalent implementation code, it’ll complain. Here, in on top of example, the lambda expression is converted to type Runnable.

In easy words, a lambda expression is AN instance of a functional interface. however, a lambda expression itself doesn’t contain the knowledge regarding that functional interface it’s implementing; that information is deduced from the context within which it’s used.

3. Java 8 lambda expression examples

Some some code samples slated down that you’ll be able to analyze and practice however it require “make you hand dirty” in writing lambda expression in day to day programming.

  • Java Lambda Expression with no parameter
   public static void main(String args[]) {
        // lambda expression
    	MyFunctionalInterface msg = () -> {
    		return "Hello";
    	};
        System.out.println(msg.sayHello());
    }
Output:
Hello

  • Java Lambda Expressions with single parameter
@FunctionalInterface
interface MyFunctionalInterface {

	//A method with single parameter
    public int incrementByFive(int a);
}
public class Example {

   public static void main(String args[]) {
        // lambda expression with single parameter num
    	MyFunctionalInterface f = (num) -> num+5;
        System.out.println(f.incrementByFive(22));
    }
}

Output:
27

  • Java Lambda Expressions example with Multiple Parameters
interface StringConcat {
    public String sconcat(String a, String b);
}
public class Example {

   public static void main(String args[]) {
        // lambda expression with multiple arguments
    	StringConcat s = (str1, str2) -> str1 + str2;
        System.out.println("Result: "+s.sconcat("Hello ", "World"));
    }
}
Output:
Hello World
  • Java Lambda Expression for Iterating over a listing 
List pointList = new ArrayList();
pointList.add("1");
pointList.add("2");

pointList.forEach(p -> {
        System.out.println(p)
    }
);

Output:

1
2

2) Java Lambda Expression to produce a new runnable and pass it to thread

new Thread(
     () -> System.out.println("My Runnable");
).start();

Output:

My Runnable

Above are very basic examples of lambda expressions in java 8.