JAVA LAMBDA EXPRESSION know-how for beginners

Tram Ho

Preface

Java Lambda Expression (Lambda expression) is a feature added to Java 8. This is a very interesting feature and it has contributed to changing the programming trend in Java. This is a feature that I think newbie should take the time to learn and understand. Honestly after 1 year of work, I didn’t know what a Lambda was. Until I joined the Java 8 project, I started contacting the Lambda expression and it completely changed my thinking and code style. In this article, I will focus on explaining in the most detailed way possible so that newbie friends can get acquainted and use the Lambda expression in their code. What I write is based on what I have learned and learned during my work so I hope it will help you. No longer, I want to start right away.

Functional Interface

Before getting acquainted with Lambda, we need to know a very important concept, Functional Interface. Functional Interface is an interface (certainly) contains only one and only one abtract method. Remember this feature: one and only one abtract method. Therefore it can also be called Single Abstract Method (SAM – the name that says it all).

Functional Interface Example:

Java 8 also introduced a new annotation @FunctionalInterface that lets us mark that interface as the Functional interface. Adding an annotation @FunctionalInterface is not required but it is necessary to declare a functional interface. Because adding @FunctionalInterface will help catch errors at compile time if you accidentally add another abstract method to the interface marked by this annotation.

Some Functional Interface declaration rules

  • A valid Functional Interface has only one abstract method.
  • A Functional Interface may have methods of the java.lang.Object class
  • The default and static method does not break the rules of the Functional interface.
  • A Functional Interface can inherit from another Functional Interface only if it doesn’t have any abstract methods
  • Functional Interface defined in Java 8 – Java Predefined-Functional Interfaces is placed in java.util.function package
  • Refer to details here

Why should we know the Functional Interface. The cause is very simple, one of the most important applications of Lambda Expression to create an instance for that interface.

Arrow operator (->)

Java 8 introduces a new operator as the arrow operator ->. This operator is used in Lambda expression with the purpose of dividing Lambda expression into 2 parts: parameter and execution content

For example:

(int a, int b) -> { do something };

What is Lambda expression and why must use Lambda expression

Lambda expression can be defined as an anonymous function. Since it is an anonymous function, it has a full set of functions that have parameters and executable content. The parameter of a function may or may not be the same as the executable content, there may be return type or no return type. Lambda expression will be based on the input parameter list and processed by the commands in the body section to produce the result.

Lambda expression provides a way to implement for the defined method at the functional interface. Besides the Lambda expression also provides libraries that help improve how to work with Collection such as browsing, filtering, and retrieving data …

With the above characteristics, Lambda helps reduce the number of lines of code. Besides, Lambda expression can also support sequential (Sequential) and parallel (Parallel) performance more efficiently via Stream API (I will not integrate Stream API related knowledge into this article. Part. The knowledge of Lambda and Steam API expressions I will introduce in the following articles)

Syntax of Lambda expression

(argument-list) -> {body}

Lambda expression in java consists of 3 components:

  • Argument-list: parameter list, may not be available, has one or more parameters.
  • Arrow-operator: The first operator is used to link the parameter list and the body of the expression.
  • Body: executable content, is a command block or an expression.
Angular4 Amazon-Web-Service Cognito-IAM-API-Lambda-IoT
Lambda’s application in Design Patterns (Part 1)

Example of Lambda expression

  • No parameters:

There are many parameters:

About declaration of parameter list:

  • Parameters separated by commas True: (int a, int b, int n) -> { doSomthing(); } Incorrect: (int a; int b; int n) -> { doSomthing(); }
  • The parameter list must be enclosed in round brackets. In case there is 1 parameter, it is not required and it is not necessary to have round brackets True: (int a, int b) -> { doSomthing(); } True: (int a) -> { doSomthing(); }Right: a -> { doSomthing(); } //best way of single param

    Incorrect: int a, int b -> { doSomthing(); }

  • Do not be forced to declare the data type of the parameter. Assuming the case of using the Lambda expression to implement function interface, the parameter’s data type will be implicitly declared at the abtract method. The removal of the parameter type declaration in Lambda expression (int a, int b) -> { doSomthing(); } or can be written as (a, b) -> { doSomthing(); }

About presenting executable content:

  • The executable content must be enclosed in curly braces. If there is a command line, it is not required. This is similar to the executable content of the if, for … command: Yes: Foo foo = parameter -> buildString(parameter); Right: Foo foo = parameter -> {buildString(parameter); return true;}
  • Where executable content consists of multiple statements, it should not be placed in Lambda expression. Lambda expressions should only have 2-5 command lines to avoid presentation complexity and purpose of using Lambda expression.

It would be better to write as follows:

Some applications of Lambda expressions

In addition to being used to implement Function interface as in the examples above, the Lambda expression is also used frequently when working with Collection. The most common is the application of Lambda expression to the forEach loop

Lambda expressions are also used to replace Anonymous inner classes. Anonymous inner class: Inner class is class (non static) written in another class (out-class). Anonymous class is an Inner class but there is no “class” before the name of the class. When doing a Collection with Collection, everyone must be exposed to an Anonymous inner class that is Comparator.

The case of using Comparator

The case of using Lambda

listDevs.sort((Developer o1, Developer o2)->o1.getAge()-o2.getAge());

Some notes when using Lambda expression

Lambda expressions are best used when combined with the Function interface. You cannot use the Lambda expression with an interface that has more than one abtract method. Notes when creating a Function interface:

  • Use @FunctionalInterface Annotation
  • Study the Functional interfaces included in the pre-initializing java.util.function package Functional interfaces to minimize unnecessary things.
  • Do not abuse default and static methods in Functional interfaces. Especially for Functional interfaces that inherit from other Functional interfaces.
  • When using the Lambda expression make sure the number of parameters and the Lambda expression return value must correspond to the only method in the Functional interfaces.

Because the Lambda expression is a feature in Java 8, make sure you have installed Java 8 or later. Lambda expression is not available for Java 7 or earlier versions.

Lambda expressions are also used to replace Anonymous inner classes. However, learn more about the difference between them to be able to use the Lambda expression appropriately.

Epilogue

The article is basic in terms of personal knowledge in the process of learning and doing as well as reading more types, so there are still many errors. Hopefully this article will help you when working with Lambda Expression. We hope you can give more suggestions.

Refer

https://gpcoder.com/3869-functional-interface-trong-java-8/

https: //.asia/p/gioi-thieu-lambda-expression-trong-java-8-EyORkbklGqB

https://blog.idrsolutions.com/2014/10/5-minutes-explanation-java-lambda-expression/

https://www.javatpoint.com/java-lambda-expressions

JAVA LAMBDA EXPRESSION know-how for beginners

Swift stepped into the top 10, Java still held the throne. “]]

Java Cheat sheet 2018 – Tips for developers
Share the news now

Source : viblo