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  


Output:


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



Employee class


Output: 


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

Redis Basic CRUD

We have seen how to setup on your linux machine here , now we will see how to perform basic CRUD operations using Spring Data & Redis server We will be creating a simple application that would persist an employee information into redis database. You will be needing certain JARs like jedis.jar, spring-data-redis.jar etc details of which you can download and view at https://github.com/meta-magic/RedisCRUDexample.git  First of all we will be creating the Employee entity, plz note that we are using the Serializable interface which automatically mapps the objects against the key. Employee.java import java.io.Serializable ; public class Employee implements Serializable { private static final long serialVersionUID = - 8243145429438016231L ; public enum Gender { Male , Female } private String id; private String name; private Gender gender; private int age; public String getId () { return id; } public void setId ( String

Eureka-Server with spring cloud netflix

In this write-up we will focus on Service Registry – Eureka Server Rest service (auth-service application, eureka client) which register itself to registry. Web application which consumes Rest service using service registry. Service discovery  allows services to find and communicate with each other without hardcoding hostname and port. Eureka Server In spring-boot application enable the Eureka-Server by adding @EnableEurekaServer annotation to spring boot application. We have put all the configuration on GIT and this is accessed using config-server. To now more about centralized configuration (config-server) click  here eurekaserver.yml Place below bootstrap.yml in application, it basically connects to config-server and gets it required configuration. Start the spring-boot application and access eureka server using http://localhost:8760/ you will get below screen. Right now there is no application which is registered to e

Redis Installation Steps

“ Redis is an in-memory key-value store known for its flexibility, performance, and wide language support” Inorder to install redis on your machine you need ubuntu 16.4 and a non-root user with sudo privileges to perform the administrative functions required for this process. Download and Extract the Source Code Create a tmp directory cd /tmp Download the latest stable version of Redis curl -O http://download.redis.io/redis-stable.tar.gz untar tar xzvf redis-stable.tar.gz Move into the Redis source directory structure that was just extracted cd redis-stable Build and Install Redis Now, we can compile the Redis binaries by typing make After the binaries are compiled, run the test suite to make sure everything was built correctly. You can do this by typing: make test This will typically take a few minutes to run. Once it is complete, you can install the binaries onto the system by typing: sudo