Skip to main content

Java 8 - Lambda Expression

 



Lambda expressions are known to be the biggest feature introduced with Java 8. This was the Java’s first step to Functional Programming.

Why Lambda Expressions :

  • Lambda Expression facilitates functional programming and simplifies the development a lot. 
  • It provides a clear and concise way to represent one method interface using an expression. It is very useful in the collection library. It helps to iterate, filter, and extract data from the collection.
  • The Lambda expression is used to provide the implementation of an interface that has a functional interface. It saves a lot of code. In the case of the lambda expression, we don't need to define the method again for providing the implementation. Here, we just write the implementation code.
  • Java lambda expression is treated as a function, so the compiler does not create a .class file.
  • They are used with functional interfaces: Lambda expressions are used with functional interfaces, which are interfaces with a single abstract method. Examples of functional interfaces include java.util.function.Consumer, java.util.function.Predicate, and java.util.function.Function.
  • Lambda expressions use the "->" operator: The "->" operator is used to separate the method signature from the lambda body. For example, (x, y) -> x + y is a lambda expression that takes two parameters x and y, and returns their sum.
  • They improve performance: Because Lambda expressions support parallelism, they can improve the performance of multi-threaded code.
  • They are backward compatible: Java 8 is backward compatible with previous versions of Java, so you can still use older Java code with Java 8 Lambda expressions.
  • Lambda Expressions enable you to encapsulate a single unit of behavior and pass it to other code. You can use lambda expressions if you want a certain action performed on each element of a collection, when a process is completed, or when a process encounters an error.

Functional Interface


A functional interface is an interface in Java that has only one abstract method. It is also known as a Single Abstract Method (SAM) interface. Functional interfaces are the cornerstone of functional programming in Java, and they are used extensively in conjunction with lambda expressions.

@FunctionalInterface
interface MyFunctionalInterface {
    void test();
}

@FunctionalInterface annotation is optional but recommended  which ensures that interface has only one abstract method.
Functional interfaces can also have default methods and static methods, but they can have only one abstract method.

Here is an example of functional interface which contains default and static method:

@FunctionalInterface
interface MyFunctionalInterface {
    void test();
    default void test() {
        System.out.println("contains default method");
    }
}


Java 8 Lambda Expression :

// syntax of lambda expressions
(parameters) - > {body}

Java Lambda Expression Syntax :

The Syntax of Lambda Expression in Java consists of three components.

parameters: It is the first portion of the Lambda expression in Java. It can also be empty or non-empty. In the expression, it is enclosed by a round bracket.
Lambda operator ->: It's an arrow sign that appears after the list of arguments. It connects the arguments-list with the body of the expression.
Body: It contains the function body of lambda expression. It is surrounded by curly brackets.


Lambda Expression Examples :

lambda expression with no parameter :
() -> {return "something"}

Lambda expression with one parameter and no return value:
(someStr) -> {system.out.println(someStr)}

Lambda expression with multiple parameter and return value:
(a, b) -> {return a+b}

Lambda expression with a block of code:
(a , b) -> {
 int mul = a*b;
 System.out.println("The multiplication is: " + mul);
return mul;
}

Lambda expression with method reference:
String[] fruits = {"Mango", "Apple", "Pineapple"};
Arrays.sort(fruits, String::toUppercase);



 




Comments

Popular posts from this blog

How to create Annotation in Spring boot

 To create Custom Annotation in JAVA, @interface keyword is used. The annotation contains :  1. Retention :  @Retention ( RetentionPolicy . RUNTIME ) It specifies that annotation should be available at runtime. 2. Target :  @Target ({ ElementType . METHOD }) It specifies that the annotation can only be applied to method. The target cane be modified to:   @Target ({ ElementType . TYPE }) for class level annotation @Target ({ ElementType . FIELD }) for field level annotation @Retention ( RetentionPolicy . RUNTIME ) @Target ({ ElementType . FIELD }) public @ interface CustomAnnotation { String value () default "default value" ; } value attribute is defined with @ CustomAnnotation annotation. If you want to use the attribute in annotation. A single attribute value. Example : public class Books {           @CustomAnnotation(value = "myBook")     public void updateBookDetail() {         ...

Kafka And Zookeeper SetUp

 Kafka And Zookeeper SetUp zookeeper download Link : https://www.apache.org/dyn/closer.lua/zookeeper/zookeeper-3.8.3/apache-zookeeper-3.8.3-bin.tar.gz Configuration: zoo.conf # The number of milliseconds of each tick tickTime =2000 # The number of ticks that the initial # synchronization phase can take initLimit =10 # The number of ticks that can pass between # sending a request and getting an acknowledgement syncLimit =5 # the directory where the snapshot is stored. # do not use /tmp for storage, /tmp here is just # example sakes. dataDir =/tmp/zookeeper # the port at which the clients will connect clientPort =2181 4 char whitelist in command arguments 4lw.commands.whitelist =* Start ZooKeeper Server $ bin/zkServer.sh start Check zookeeper status dheeraj.kumar@Dheeraj-Kumar bin % echo stat | nc localhost 2181 stat is 4 character whitelisted argument  Check Kafka running status : echo dump | nc localhost 2181 | grep broker Responsibility of Leader in Zookeeper: 1. Distrib...

Auto retries in REST API clients On Java On Ease

  Writing REST clients to consume API endpoints has become commonplace. While consuming REST endpoints, we sometimes end up in a situation where a downstream service throws some kind of transient error that goes away when the API call is retried. In such situations, we ask ourselves — “What if my API client was smart enough that knew how to retry a failed call?” Some of us go the extra mile to implement our own custom code that can retry API calls on error. But mind you, it is not only about knowing how to retry. The client also has to know when to retry and when not to. If the error is irrecoverable such as 400 — Bad Request, there is no point in retrying. It might also have to know how to back off and how to recover from the error. Implementing all this by hand, and then repeating it over and over again in every API client is cumbersome. It also adds a lot of boilerplate code and makes things even worse. But if you are a Spring/Spring Boot developer, you will be surprised to know...