Using Lambda Expressions In Java

By bhagwatchouhan
Using Lambda Expressions In Java

Lambda Expressions were added in Java since Java 8. It's a short block of code that takes either zero, single, or multiple arguments and executes either single or multiple statements which might return value according to the functional interface method signature. This tutorial provides the syntax and details about using the Lambda Expressions in Java with examples.

 

Syntax

 

This section provides the syntax to be followed by the lambda expressions.

 

The simplest lambda expression with one argument and expression resulting in either true or false or expression result is shown below.

 

// One argument with Expression
argument -> expression

// Example - Comparison - return true or false
n -> n < 10

// Example - Addition - returns value
n -> n + 10

 

The lambda expression can also be associated with multiple arguments and expression resulting in either true or false or the expression result is shown below.

 

// Multiple arguments with Expression
(argument1, argument2) -> expression

// Example - Comparison - return true or false
(n, m) -> n < m

// Example - Addition - returns value
(n, m) -> n + m

// Exampe - Without Arguments
() -> System.out.println( "Hello World !!" )

 

The lambda expression can also have either single or multiple arguments and expression body returning the value according to the functional interface method signature.

 

// Lambda Expression with Body
(argument1, argument2) -> { code block }

// Example
(n, m) -> n + m
// OR
(int n, int m) -> n + m
// OR
(n, m) -> { int sum = n + m; return sum; }
// OR
(int n, int m) -> { int sum = n + m; System.out.println( "Sum: " + sum ); }

 

Rules

 

The simple rules followed by the Lambda Expressions are listed below.

 

  • The Lambda Expressions are similar to methods without any name. In other programming languages, it's also known as closure.
  • The Lambda Expression can be associated with either single or multiple arguments.
  • Parentheses are required for a single argument specifying the argument type.
  • Parentheses are required for multiple arguments.
  • Parentheses are required for zero arguments.
  • The multiple arguments may specify the type.
  • The expression can perform simple operations and it might return a value.
  • The expression can be a block of code having multiple statements.
  • Curly braces are optional in case of a simple expression having a single statement.

 

Simple Usage

 

This section provides a fully functional example showing the simplest usage of the Lambda Expression.

 

public class LambdaExpressionDemo {

public static void main( String[] args ) {

MathOps sum = ( int n, int m ) -> { int result = n + m; return result; };
MathOps sub = ( n, m ) -> { int result = n - m; return result; };

System.out.println( "Sum: " + ( sum.operation( 10, 20 ) ) );
System.out.println( "Sub: " + ( sub.operation( 20, 10 ) ) );
}
}

interface MathOps {

int operation( int n, int m );
}

 

The output of the above program is shown below.

 

// Output
Sum: 30
Sub: 10

 

A slight variation to the above program is shown below. In this variation, the Lambda Expression is not returning any value following the functional interface method. It simply prints the output.

 

public class LambdaExpressionDemo {

public static void main( String[] args ) {

MathOps sum = ( n, m ) -> { int result = n + m; System.out.println( "Sum: " + result ); };
MathOps sub = ( int n, int m ) -> { int result = n - m; System.out.println( "Sub: " + result ); };

sum.operation( 10, 20 );
sub.operation( 20, 10 );
}
}

interface MathOps {

void operation( int n, int m );
}

 

The output of the above program is shown below.

 

// Output
Sum: 30
Sub: 10

 

Another simple example of the Lambda Expression with zero arguments is shown below.

 

public class LambdaExpressionDemo {

public static void main( String[] args ) {

SimpleOps simple1 = () -> { System.out.println( "Hello World !!" ); };

simple1.operation();
}
}

interface SimpleOps {

void operation();
}

 

The output of the above program is shown below.

 

// Output
Hello World !!

 

Advanced Usage

 

This section provides a fully functional example code showing the usage of Lambda Expressions. I have used the class Person to store the names and ages of all the people. The interface Tester is used as the functional interface for the Lambda Expression.

 

The main method of the class LambdaExpressionDemo creates the people database and also queries the database to get the list of persons older than 30. It finally prints the name of all the persons and the persons having age greater than 30.

 

import java.util.ArrayList;

/**
* The LambdaExpressionDemo class creates a people database and queries the db older than 30.
*
* It finally prints the name of all the persons and the persons older than 30.
*/
public class LambdaExpressionDemo {

public static void main( String[] args ) {

ArrayList<Person> personDb = new ArrayList<>();

personDb.add( new Person( "Joe", 12 ) );
personDb.add( new Person( "Ravi", 45 ) );
personDb.add( new Person( "Nicolas", 32 ) );
personDb.add( new Person( "Sachin", 42 ) );
personDb.add( new Person( "Tim", 25 ) );
personDb.add( new Person( "Ravi", 45 ) );
personDb.add( new Person( "Bayo", 38 ) );

ArrayList<Person> olderThan30 = testAge( personDb, p -> p.getAge() > 30 );
// ArrayList<Person> olderThan30 = testAge( personDb, p -> { return p.getAge() > 30; } );

System.out.println( "All Person: " + personDb );

System.out.println( "Older than 30: " + olderThan30 );
}

public static ArrayList<Person> testAge( ArrayList<Person> list, Tester<Person> expr ) {

ArrayList<Person> result = new ArrayList<>();

for( Person p : list ) {

if( expr.testAge( p ) ) {

result.add( p );
}
}

return result;
}
}

interface Tester<Person> {

boolean testAge( Person p );
}

class Person {

private String name;
private int age;

public Person( String name, int age ) {

this.name = name;
this.age = age;
}

public void setName( String name ) {

this.name = name;
}

public String getName() {

return name;
}

public void setAge( int age ) {

this.age = age;
}

public int getAge() {

return age;
}

public String toString() {

return name;
}
}

 

The result after executing the program is shown below.

 

// Result
All Person: [Joe, Ravi, Nicolas, Sachin, Tim, Ravi, Bayo]
Older than 30: [Ravi, Nicolas, Sachin, Ravi, Bayo]

 

Summary

 

This tutorial provided the syntax and rules to be followed by the Lamda Expressions in Java. It also provided the example showing the usage of the Lambda Expressions.

share on :

Profile picture for user bhagwatchouhan
bhagwatchouhan