Java lambda expression

What is a lambda expression?

This is the description method introduced in Java 8. The Stream API [^ 1], also introduced in Java 8, is premised on using lambda expressions, so learning lambda expressions seems to be beneficial.

[^ 1]: An API for handling collections such as arrays and lists, which allows you to implement value aggregation and data processing with easy-to-understand code.

Another advantage of using lambda expressions is that you can simplify "writing functional interfaces using anonymous classes."

How to write a lambda expression

The basic way to write a lambda expression is as follows.

Interface name Object name=Argument (can receive multiple)->processing;

You don't need to specify the argument type as the compiler will type infer it for you. ~~ When there is only one argument, there is no need to return, enclose the argument (), write the process {}, etc. ~~ ※correction You can omit {} and return if there is only one sentence in {} that says return ~. The number of arguments doesn't matter.

Implementation using anonymous classes

Anonymous class is the local class that implements the interface, omitting the declaration part. Lambda expressions allow you to write concisely and clearly without using anonymous classes.

For example, if you have the following anonymous class:

main.java



interface InterfaceTest{
    //Abstract method
    public String name(String name);
}
 
public class Main {
 
    public static void main(String[] args) {
 
        //How to write using anonymous classes
        InterfaceTest greeting = new InterfaceTest() {
            //override
            public String name(String name) {
                return "Hello " + name;
            }
        };
        System.out.println(greeting.name("momoji"));
    }
 
}

In the above, it looks like you're instantiating an interface, but you're actually instantiating an anonymous class with an interface.

Execution result ↓

Hello momoji

Lambda-style implementation

Let's rewrite this with a lambda expression.

main.java


interface InterfaceTest{
    //Abstract method
    public String name(String name);
}
 
public class Main {
 
    public static void main(String[] args) {
 
        //How to write using a lambda expression
        InterfaceTest greeting = (name) -> {
            return "Hello " + name;
        };
        System.out.println(greeting.name("momoji"));
    }
 
}

The processing contents to be performed by the greeting method are described in {}. It's shorter and it's easier to see what you're doing. Also, you no longer have to specify the argument type.

Execution result ↓

Hello momoji

Write the forEach statement shorter using a lambda expression

Java has the same properties as a for-each statement, and there is an extended for statement. It has the property of performing the specified processing for all elements of an array or list.

How to write an extended for statement

for (Data type variable name:list and array){
processing;
  ...
}

To output all the elements of the list in order, write the following in the extended for statement.

main.java


main.java
class Main {
    public static void main (String[] args) {

            List<String> list = new ArrayList<>();
            list.add("a");
            list.add("b");
            list.add("c");

            //Extended for statement
            for(String l : list) {
                System.out.println(l);
            }

        }
}

In the above example (1) Define a String type list "list" (2) Use the add method to fill the list with the elements "a", "b", and "c" one by one. (3) Output the list elements one by one using the extended for statement.

I am doing that.

The execution result is as follows.

a
b
c

This can be made even shorter with lambda expressions and foreach statements.

main.java


class Main {
    public static void main (String[] args) {
 
            List<String> list = new ArrayList<>();
            list.add("a");
            list.add("b");
            list.add("c");
            
            //Extended for statement
            // for(String l : list) {
            //  System.out.println(l);
            // }

            //For Each statement using a lambda expression
            list.forEach(l -> System.out.println(l));
            
        }
}

Execution result ↓

a
b
c

I was able to fit what I was writing by exercising 3 in one line. You can make this even shorter by using "method references".

What is a method reference?

This is also a notation introduced from Java 8. A method reference is a mechanism that allows you to refer to a method as an argument of the method. You can call a predefined method with no arguments.

The method reference is written as follows.

name of the class::Method name

After the class name, write "::" and the name of the method you want to call. No () is required in the method name.

I will combine it with a lambda expression at once.

main.java


//Lambda expression with method reference
list.forEach(System.out::println);

Execution result ↓

a
b
c

The combination of lambda expressions and method references has made it possible to write much shorter.

Recommended Posts

[Java] Lambda expression
Java lambda expression
Java lambda expression variations
Java 8 lambda expression Feature
Java lambda expression [memo]
Review java8 ~ Lambda expression ~
Java lambda expression again
[Java] Functional interface / lambda expression
Java8 stream, lambda expression summary
Java basic learning content 9 (lambda expression)
Hello Java Lambda
What is a lambda expression (Java)
Now let's recap the Java lambda expression
Quarkus saves Java Lambda! ??
Understand Java 8 lambda expressions
About Java lambda expressions
Introduction to lambda expression
Explain Java 8 lambda expressions
Java table expression injection
java regular expression summary
Java Lambda Command Pattern
How to use Java API with lambda expression
Java8 to start now ~ forEach and lambda expression ~
Java8 Lambda expression & Stream design pattern reconsideration --Command pattern -
[Java] Introduction to lambda expressions
What is a lambda expression?
Java
Getting Started with Legacy Java Engineers (Stream + Lambda Expression)
Java
Java8 Lambda Expression & Stream Design Pattern Rethinking --Null Object Pattern -
Java8 Lambda expression & Stream design pattern reconsideration --Template Method pattern -
Assign a Java8 lambda expression to a variable and reuse it
Java8 Lambda Expression & Stream Design Pattern Rethinking --Chain of Responsibility Pattern -
[Introduction to Java] About lambda expressions
About Lambda, Stream, LocalDate of Java8
Is Java on AWS Lambda slow?
Hello World on AWS Lambda + Java
Try an If expression in Java
Getting started with Java lambda expressions
The origin of Java lambda expressions
How to use Java lambda expressions
Java learning (0)
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
Implement API Gateway Lambda Authorizer in Java Lambda
java (constructor)
Java array
java (override)
java (method)
Java Day 2018
Java string
Java static