Java 8 – Lambda Expression

In this article, we will discuss one of the important feature introduced in Java 1.8 version i.e.; Lambda Expression.

History about Lambda expression

Unlike other new features introduced by Java ecosystem in the past till Java 1.7 version, this is not new feature to the programming world. Rather it is old feature which is extensively used in other programming language like LISP, C++, Ruby, Scala, Python, etc. This was introduced in March 18, 2018.

Lambda Expression in Java 1.8 version

It is introduced in Java ecosystem to bring benefits of Functional programming concepts. Let us look at attributes about it,

  • It is an anonymous function or nameless i.e.; a method without name
  • Return type is not required, as it could be inferred during course of program execution
  • Absolutely not required to mention access-modifiers, as it will be local to where it is declared/defined. But declaring doesn’t result into any error.

So what is actually required to denote/identify a Lambda expression,

  • arguments lists, if any otherwise empty parenthesis ( )
  • execution part or logic or body or set of correct java statement

Lambda expression syntax or denotion

(argument list)->{function_body};

Where,

  • argument lists is number of input arguments or parameter
  • function body (method implementation) is set of Java statement within curly braces
  • And there is special symbol for Lambda expression that is hyphen followed by greater than sign i.e.; ->
    Example – (argument_list) -> {method_body};
  • There are certain rules regarding above syntax (->) which we will discuss at the end of this topic

Method to Lambda Expression conversion :

Before, we divulge more into real example we will look at how can we convert Java methods into Lambda Expression which is more concise means less code.

A normal method in Java contains following things,

  • access modifier
  • return type
  • method name
  • argument lists
  • method body

But Lambda Expression consists following things only,

  • input arguments list inside parenthesis
  • method body within curly braces

Example 1: TestLambdaExpression.java

  • Below is the standard method in Java to print “Hello World”
// normal Java method to print sysout
     public void print() {
         System.out.println("Hello World");
     }

Let us look at Lambda Expression for the above method with working code

  • Here, it prints “Hello World” to console using lambda expression
package net.bench.resources.java8;

@FunctionalInterface
interface DemoInterface {
	public void display();
}

public class TestLambdaExpression {

	// main method
	public static void main(String[] args) {

		// Lambda Expression equivalent for above method
		DemoInterface d = () -> System.out.println("Hello World");

		// how to invoke Lambda Expression -> Functional Interface
		d.display();
	}
}

Output:

Hello World

More examples to follow

Example 2: TestLambdaExpression.java – with return keyword

  • This example takes one input argument and returns square of input argument
// Java method to return square of n
	public int square(int n) {
		return n*n;
	}

Let us look at Lambda Expression for the above method with working code

  • Here, it takes an integer value 5 and calculate square value
  • Note: Since we are using return keyword, we have to put java statements inside curly braces even if it consists of single line of code
package net.bench.resources.java8;

@FunctionalInterface
interface DemoInterface {
	public int square(int n);
}

public class TestLambdaExpression {

	// main method
	public static void main(String[] args) {

		// Lambda Expression equivalent for above method
		DemoInterface d = (n) -> {return n*n;};

		// how to invoke Lambda Expression -> Functional Interface
		System.out.println(d.square(5));
	}
}

Output:

25

Example 3: TestLambdaExpression.java – without return keyword

  • This example takes two input argument and returns sum of input arguments
  • In the above example, we are explicitly returning value after calculation so we must use return keyword that too inside curly braces
  • In below example, we are not explicitly returning value rather lambda expression infers and return
  • This time we don’t need curly braces as there is no return keyword unlike above example
public int sum(int a, int b) {
		return a+b;
	}

Let us look at Lambda Expression for the above method with working code

  • Here, it takes 2 integer values and calculate their sum
package net.bench.resources.java8;

@FunctionalInterface
interface DemoInterface {
	public int add(int n1, int n2);
}

public class TestLambdaExpression {

	// main method
	public static void main(String[] args) {

		// Lambda Expression equivalent for above method
		DemoInterface d = (n1, n2) -> n1+n2;

		// how to invoke Lambda Expression -> Functional Interface
		System.out.println(d.add(13, 17));
	}
}

Output:

30

Example 4: TestLambdaExpression.java – without return keyword

  • This example takes one String argument and returns length of the same of String
  • Again, here return type is inferred by lambda expression based on value it returns
  • So, not explicitly returning using return keyword and therefore no need of curly braces for one line of java statement
public int getStringLength(String s) {
		return s.length();
	}

Let us look at Lambda Expression for the above method with working code

  • Here, it takes a String value “BenchResources.Net” and calculate its length
package net.bench.resources.java8;

@FunctionalInterface
interface DemoInterface {
	public int length(String s);
}

public class TestLambdaExpression {

	// main method
	public static void main(String[] args) {

		// Lambda Expression equivalent for above method
		DemoInterface d = (s) -> s.length();

		// how to invoke Lambda Expression -> Functional Interface
		System.out.println(d.length("BenchResources.Net"));
	}
}

Output:

18

How to call/invoke Lambda Expression ?

  • To invoke any Lambda Expression, we need Functional Interface
  • As you see in above examples, every example contains an interface which is annotated with @FunctionalInterface
  • And each interface consists of only one abstract method
  • An interface which contains only one abstract method is called as Functional Interface
  • Already known Functional Interfaces in java are Runnable, Callable, Comparable. Comparator which contains exactly one method like run(), call(), compareTo(), compare() respectively

Important points to remember while writing Lambda Expression

  • To call Lambda Expression, Functional interface is must which consists of single abstract method
  • For method body, curly braces is optional if it consists of single Java statement; otherwise curly braces is must for more than 2 statements
  • Similarly, parenthesis is optional if it consists of single input arguments; otherwise it is must for all other cases even if it doesn’t accepts any input arguments like empty parenthesis ( )
  • Specifying access-specifier for input arguments is optional, as it can be inferred from the value passed to lambda expression
  • While returning value, return keyword is optional if we are not using curly braces and it consists of single Java statement; otherwise it is must for all other cases

Is it necessary to write Functional Interface every time for example ?

References:

Happy Coding !!
Happy Learning !!

Java 8 - Functional Interface in Java
How to sort HashSet in Java 8 ?