Apps/Gaming

Working with Lambda Expressions in Java

In Java, a lambda is a block of code that accepts arguments and returns a value. The lambda expression was originally introduced in Java 8 and improves the expression capabilities of Java. This article is about lambda expressions and how we can work with them in Java.

What is a lambda expression?

Lambda expressions are anonymous methods that have no name and belong to any class. Lambda expressions are part of the java.util.function package. You can use lambda expressions in Java to implement callbacks

Lambda expressions are the building blocks of functional programming in Java. Each lambda expression is internally assigned to a functional interface. When compiling the source code, the compiler decides from the context on which functional interface it should be mapped.

Unlike other functions in Java, you can define Lambda functions that exist outside the scope of any object. This allows Lambda functions to be called and passed anywhere in the program. For example, it is possible to pass a lambda function as an argument to another function.

Why do we need lambda expressions?

Java is a higher programming language This is object-oriented and class related. This means that in addition to the basic data types in Java, everything is somehow an object. You cannot define top-level functions in Java; You cannot define a function outside of a class. In addition, Java does not allow you to return a function from another function or pass an argument to another function. This is where lambda expressions help.

Read: An introduction to the Lambda architecture

Characteristics of Lambda Functions in Java

A lambda expression can contain zero, one or more parameters:

  • You can either declare the parameter type explicitly or derive it from the context.
  • If you have multiple parameters in a lambda expression, separate them with commas and enclose them in parentheses.
  • If there are no parameters, that is, an empty set of parameters, you can represent it with empty brackets.
  • Having a single parameter in a lambda expression eliminates the need for parentheses when inferring the type.
  • The body of the lambda expression cannot contain any statements or contain single or multiple statements.
  • You must use curly braces when the body of an expression contains multiple statements.
  • There is no point in using curly braces when there is only one statement in the body of the lambda expression.

What is a functional interface in Java?

A functional interface consists of a single abstract method and no other methods. An example of a functional interface is the runnable interface, which is part of the java.lang package. The runnable interface contains only one method, that is, the run () method.

This is what the definition of the runnable interface looks like in C #:

@FunctionalInterface public interface Runnable {public summary void run (); }

Like the runnable interface, Comparator is another functional interface that only contains an abstract method, Compare ().

Here are some examples of the functional interfaces added in Java 8:

public interface predicate {boolean test (T t); } public interface function {Apply R (Tt); } public interface BinaryOperator {T apply (T left, T right); } public interface consumer {accept void (T t); } public interface supplier {T get (); }

Read: Understanding of Lambda-enabled design patterns

Programming lambda expressions in Java

syntax

Here is the syntax for defining a lambda function:

Parameter -> expression

The following statement shows how you can define a lambda expression:

(Type arg1, type arg2, type arg3, …) -> (text)

Note that you do not need to specify the type declaration because the Java compiler can infer the argument types from the context. Here is an example that illustrates this:

(arg1, arg2, arg3, …) -> (body)

The lambda operator in Java

The Java programming language introduces the lambda operator to work with lambda expressions. There are two options for creating a lambda expression: create your functional interface or use a predefined functional interface that is available.

The arrow operator is used to represent lambda expressions in Java. Here is an example that shows this:

(x) -> x * x;

The left side of the arrow operator is used to specify the parameters. This can even be empty, meaning you can have a lambda expression that has no parameters. The right side of the arrow operator is used to indicate the body of the lambda expression.

Read: Java lambda expressions revisited

Java Lambda Expression Code Examples

The following code snippet illustrates a lambda expression that takes no parameters:

() -> System.out.println (“This is an example of a lambda expression without parameters”);

The following code snippet is an example of a two-parameter lambda expression:

(int x, int y) -> x + y;

Passing lambda expressions as arguments

You can pass lambda expressions as arguments to a function. If you need to pass a lambda expression as a parameter, the parameter type should be able to take it. When passing an integer as an argument to a function, it must have an int or integer parameter. If you pass an instance of a class as a parameter, you must specify the class name or the object class as a parameter for the object.

There is no type for the lambda expression in Java. Instead, it would be helpful if you used an interface, that is, a functional interface, to accept the parameter.

The following code list illustrates a lambda expression and simple functional interface that includes an abstract function and a standard non-abstract function:

Interface MyFunctionInterface {void abstractFunction (int x); default void nonAbstractFunction () {System.out.println (“Hello world!”); }} public class LambdaExpressionDemo {public static void main (String args[]) {MyFunctionInterface functionObj = (int x) -> System.out.println (x * x); functionObj.abstractFunction (5); }}

It should be noted here that adding too many standard methods in a functional interface is not a good choice. Here is an example that shows how you can pass a lambda expression as a parameter to the replaceAll () method.

import java.util.ArrayList; public class Main {public static void main (String[] args) {ArrayList-Cities = new ArrayList <> (); Cities.add (“London”); Cities.add (“Tokyo”); Cities.add (“New York”); Cities.replaceAll (e -> e.toUpperCase ()); System.out.println (“names of cities in UPPER CASE:” + cities); }}

Java Lambda Expression Best Practices

Here are some best practices to keep in mind when working with lambda expressions in Java:

  • It has proven effective to use functional standard interfaces
  • You should keep your lambda expressions short
  • Avoid excessive use of standard methods in functional interfaces
  • Avoid specifying parameter types
  • Use lambda expressions to instantiate functional interfaces
  • Avoid overloading methods that have functional interfaces as parameters

Summary of lambda expressions in Java

In Java, lambda expressions are represented as objects, so they need to be mapped to a specific object type. This is the target type or the functional interface.

If both the target type of the lambda and the arguments captured are serializable, then the lambda can be serialized. The serialization of lambda expressions, on the other hand, is strongly discouraged, as is the case with inner classes.

The lambda expression was one of the most important innovations in Java 8. It marked the beginning of the transition from object-oriented to functional programming in Java.

Read more tutorials and guides on Java programming.

Related posts

Best Kanban Tools for Developers

TechLifely

An Introduction to Kubernetes

TechLifely

Overview of Prince2 Project Management

TechLifely

Leave a Comment