[Java] Java lambda expression

3 minute read

What is a lambda expression

The description method introduced in Java8. Similarly, the Stream API 1 introduced in Java8 is based on the assumption that lambda expressions are used, so there seems to be merit in learning lambda expressions.

Using lambda expressions also has the advantage of simplifying “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) -> process;

You don’t need to specify the argument types, as the compiler will infer them. ~~ If there is only one argument, you do not need to return, enclose the argument (), write the process {}, etc. ~~ ※correction You can omit {} and return when {} contains only one statement, return ~. The number of arguments does not matter.

Implementation using anonymous class

Anonymous (anonymous) class is a local class that implements an interface, with the declaration part omitted. Lambda expressions allow you to write concisely and easily 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 class
        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 are instantiating an interface, but you are actually instantiating an anonymous class with the interface.

Execution result↓

Hello momoji

Implementation with lambda expression

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) {
 
        // Writing with a lambda expression
        InterfaceTest greeting = (name) -> {
            return "Hello" + name;
        };
        System.out.println(greeting.name("momoji"));
    }
 
}

The contents of processing performed by the greeting method are written in {}. It’s shorter, and it’s easier to see what you’re doing. Also, it is no longer necessary to specify the argument type.

Execution result↓

Hello momoji

Write a ##forEach statement shorter with a lambda expression

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

How to write extended for

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

To output all list elements in order, use the extended for statement as follows.

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, ①Define a String type list “list” ② Add “a”, “b”, “c” elements to the list one by one with the add method ③ Output the elements of list 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);
            //}

            // forEach statement with lambda expression
            list.forEach(l -> System.out.println(l));
            
        }
}

Execution result↓

a
b
c

3 I was able to put what I was exercising and writing into one line. You can make this even shorter by using “method references”.

What is a method reference?

This is also the notation introduced in Java 8. Method reference is a mechanism that allows you to refer to a method as an argument. You can call a defined method with no arguments.

Method reference is written as follows.

Class name :: method name

After the class name, write “::” and the method name you want to call. () is not required in the method name.

Let’s combine it with the lambda expression.

main.java


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

Execution result↓

a
b
c

With the technique of combining lambda expressions and method references, it is now possible to write very shortly.

  1. API for handling collections such as arrays and lists. API that allows you to implement value aggregation and data processing with easy-to-understand code.