Skip to main content

Java 8 - Lambda Expression

Java 8 Lambda Expression

What is lambda expression ?

In mathematics and computing generally, a lambda expression is a function for some or all combinations of input values it specifies an output value. Lambda expressions in Java introduce the idea of functions into the language. In conventional Java terms lambdas can be understood as a kind of anonymous method with a more compact syntax that also allows the omission of modifiers, return type, and in some cases parameter types as well.

The problem of bulky syntax is refereed as “Vertical Problem” by Java people and Java 8 provides a Lambda expression to gives a very simple yet powerful functional programming capability to Java.


Functional Interface

Functional interfaces have a single functionality to exhibit. An interface which has only one abstract method is called functional interface. For example, a Comparable interface with a single method ‘compareTo’ is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions. Java provides an annotation @FunctionalInterface, which is used to declare an interface as functional interface.

Syntax

The basic syntax of a lambda is either

(parameters) -> expression
or
(parameters) -> { statements; }
  • A comma-separated list of formal parameters enclosed in parentheses. It can be empty.
  • The arrow token, -> 
  • Body of the lambda expression contains expression and statements.

 

Ways to write Lambda Expression

  • (int x, int y) -> x + y    - takes two integers and returns their sum.
  • (x, y) -> x - y                - two numbers and returns their difference.
  • () -> 42                        - takes no values and returns 42.
  • (String s) -> System.out.println(s) - takes a string, prints its value to the console, and returns nothing. 
  • x -> 2 * x                    - takes a number and returns the result of doubling it.
  • c -> { int s = c.size(); c.clear(); return s; } - takes a collection, clears it, and returns its previous size

When ?

Lambda is replacement of Anonymous class? NO, Lambdas are anonymous functions which are designed to eliminate overhead (Constructor and other bulky code) of Anonymous class where it is not required.

Why ?

There are various reasons for addition of lambda expression in Java platform but the most beneficial of them is that we can easily distribute processing of collection over multiple threads. Prior to Java 8, if the processing of elements in a collection had to be done in parallel, the client code was supposed to perform the necessary steps and not the collection. In Java 8, using lambda expression and Stream API we can pass processing logic of elements into methods provided by collections and now collection is responsible for parallel processing of elements and not the client.
Also, parallel processing effectively utilizes multi core CPUs used nowadays

 

Where ?

Lambda expressions can be used anywhere in Java 8 where we have a target type. In Java, we have target type in the following contexts
  • Variable declarations and assignments
  • Return statements 
  • Method or constructor arguments

 

Example

1. Calculator  

public class Calculator {
@FunctionalInterface
interface MathOperation {
int operation(int number1, int number2);
}
public int operate(int a, int b, MathOperation mathOperation) {
return mathOperation.operation(a, b);
}
private void addition() {
MathOperation additionOp = (number1, number2) -> number1 + number2;
System.out.println("50 + 10 = " + operate(50, 10, additionOp));
}
private void subtraction() {
MathOperation subtractionOp = (number1, number2) -> number1 - number2;
System.out.println("50 - 10 = " + operate(50, 10, subtractionOp));
}
private void multiplication() {
MathOperation multiplicationOp = (number1, number2) -> number1 * number2;
System.out.println("50 * 10 = " + operate(50, 10, multiplicationOp));
}
private void division() {
MathOperation divisionOp = (number1, number2) -> number1 / number2;
System.out.println("50 / 10 = " + operate(50, 10, divisionOp));
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.addition();
calculator.subtraction();
calculator.multiplication();
calculator.division();
}
}
view raw Calculator.java hosted with ❤ by GitHub

Output:

50 + 10 = 60
50 - 10 = 40
50 * 10 = 500
50 / 10 = 5

Example Notes: 

  • MathOperation is the FunctionalInterface having single functionality named operation to perform mathematical operations on two numbers. 
  • Operate method used for the invocation of operation.
  • Addition, Subtraction, Multiplication and Division are the four private methods to perform operation according to their name on two Integers using Lambda Expression with its target and anonymous method named operation.

2. Sorting 

Example to sort employees by their salary


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Sorting {
private static void sortEmployees(List<Employee> employees) {
Collections.sort(employees, (left, right) -> left.getSalary().compareTo(right.getSalary()));
}
public static void main(String[] args) {
final List<Employee> employees = new ArrayList<>();
employees.add(new Employee(101, "EMP1", 400000l));
employees.add(new Employee(102, "EMP2", 360000l));
employees.add(new Employee(103, "EMP3", 800000l));
employees.add(new Employee(104, "EMP4", 600000l));
employees.add(new Employee(105, "EMP5", 500000l));
System.out.println("*****Employees*****\n" + employees);
sortEmployees(employees);
System.out.println("*****SORTED BY SALARY*****\n" + employees);
}
}
view raw Sorting.java hosted with ❤ by GitHub

Employee class

final public class Employee {
final private Integer employeeCode;
final private String employeeName;
final private Long salary;
public Employee(Integer employeeCode, String employeeName, Long salary) {
super();
this.employeeCode = employeeCode;
this.employeeName = employeeName;
this.salary = salary;
}
public Integer getEmployeeCode() {
return employeeCode;
}
public String getEmployeeName() {
return employeeName;
}
public Long getSalary() {
return salary;
}
@Override
public String toString() {
return "[" + employeeName + " " + salary + "]";
}
}
view raw Employee.java hosted with ❤ by GitHub

Output: 

*****Employees*****
[[EMP1 400000], [EMP2 360000], [EMP3 800000], [EMP4 600000], [EMP5 500000]]
*****SORTED BY SALARY*****
[[EMP2 360000], [EMP1 400000], [EMP5 500000], [EMP4 600000], [EMP3 800000]]

Example Notes:

  • We have taken 5 dummy records of employees with its parameters employee code, name and salary.
  • Static function sortEmployees used to sort the employees by comparator using lambda expression.

Comments

Popular posts from this blog

Centralized configuration using Spring Cloud Config

In this blog we will be focusing on centralized configuration using  Spring Cloud Config  project. For single standalone application we can keep all required configuration bundle with application itself.  However, when we have more than one application, say in a microservice architecture, a better alternative would be to manage the configurations centrally. With the Config Server we have a central place to manage external properties for applications with support for different environments. Configuration files in several formats like YAML or properties are added to a Git repository. Features Spring Cloud Config Server features: HTTP, resource-based API for external configuration (name-value pairs, or equivalent YAML content) Encrypt and decrypt property values (symmetric or asymmetric) Embeddable easily in a Spring Boot application using  @EnableConfigServer Config Client features (for Spring applications): Bind to the Config Server and initialize...

Function Point Analysis : ISO/IEC 20926:2009

This blog focuses on explaining the Function Point calculations. Software Sizing Background Function Point Rules for Counting FP Deep Dive - Function Point Analysis Case Study General Software Characteristics Details History - Measurement Methodologies Lines of Code (Oldest) Use case based Software Sizing IPFUG Function Point Analysis (ISO) Need for Software Sizing. Estimation and Budgeting Phasing Development Work Prioritization of Work Monitoring the Progress Bidding for Projects Allocating Testing Resources To measure and Manage Productivity Risk Assessment Software Asset Valuation CMMi Level 2 and 3 require that a valid sizing method be used. Software Sizing - Lines of Code The easiest and historically the most common method in Sizing Software project has been counting the number of lines of code and / or the number of screens. Advantages Automation of the counting process can be done Intuitive as the measurements are easily u...

CRUD in MongoDB & Spring Data

Now, since we have already been introduced to mongo and its server is setup. We shall now move on to performing basic CRUD operations. Lets take a use case example of ‘Company’ database that stores employee information.  We wish to store employee name, email address, age and multiple addresses. Traditionally in RDBMS we would create an Employee table and Address Table having foreign key reference to ‘employee id ‘ Incase of NoSQL, we will be creating Employee documnet which will have store employee information like name, email, age and an array of employes address. Following is a snippet of the schema defined { "name" : "", "email" : "", "age" : “”, "address" : [ ... ] } Thus to begin with, we will first define the entities. We have employee as an aggregate root entity that stores list of address having 1-M relatioship. Address Entity is represend as @Embeddable as it is embaded in another aggregate root entity. Employee is...