[JAVA] Introduction to lambda expression

Why use lambda expressions?

Java, which is used for large-scale development, requires that the amount of code be reduced as much as possible and that it be easy to read. The "lambda expression" used in Java 8 is useful for such occasions. A feature of lambda expressions is that you can treat methods like variables.

How to write:

[Interface declaration]= (argument)->{Execution block}

Let's check it from the source code at once. First of all, the traditional expression:


public class LambdaTest {

    public static void main(String[] args) {
        //Traditional expression
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("threading" + Thread.currentThread().getId());
            }
        }).start();
    }
}

The following is a representation of a Lambda expression.


public class LambdaTest {

    public static void main(String[] args) {
        //Lambda expression
        new Thread(() -> {
            System.out.println("Lambda threading" + Thread.currentThread().getId());
        }).start();
    }
}

Java functional interface

Java's functional interface is almost the same as a traditional interface, but the only feature is that the functional interface is "an interface with only one abstract method defined". Static methods and default methods can be included. (It's a good idea to annotate java.lang.FunctionalInterface).

See the detailed introduction to the Java function interface. https://qiita.com/Jenny1025/items/470e304ff77c44874fc8

Example:

@FunctionalInterface
public interface UserIdentify {
    String verifyUser(String userName);
}

Benefits of Lambda expressions

The advantage of Java's Lambda expression is that it can simplify the description of functional interfaces using anonymous classes.

Anonymous class:

public class App 
{
    public static void main( String[] args ) {

        //Functional interface
        UserIdentify ic = new UserIdentify() {
            @Override
            public String verifyUser(String userName) {
                return "admin".equals(userName)? "admin":"member";
            }
        };

        System.out.println(ic.verifyUser("admin"));
        System.out.println(ic.verifyUser("manager"));
        }
    }

So how do you express it in a Lambda expression?

public class App {
    public static void main( String[] args ) {
        
        UserIdentify ic1 = (String userName) -> {
                return "admin".equals(userName)? "admin":"member";
            };
        System.out.println(ic1.verifyUser("admin"));
        System.out.println(ic1.verifyUser("manager"));
        }
    }

Specific explanation of how to write a lambda expression

  1. Declaration: Lambda-style interface type
  2. Arguments: Enter in (). Same as the number and order of interface arguments
  3. Expression:->
  4. Execution block: Implemented in {}

Let's start with a concrete example.

No arguments, no return value

public class App {
    public static void main( String[] args ) {

        //No arguments, no return value
        Lambda1 lambda1 = () -> System.out.println("Hello world");
        lambda1.test();
    }
    interface Lambda1 {
        void test();
    }
}

Implementation result: Hello world

With arguments, no return value

public class App {
    public static void main( String[] args ) {

        //With arguments, no return value
        Lambda2 lambda2 = (n, a) -> System.out.println(n + " is " + a + " years old");
        lambda2.test("Sally",18);
    }
    interface Lambda2 {
        void test(String name, Integer age);
    }
}

Implementation result: Sally is 18 years old

With arguments, with return value

public class App {
    public static void main( String[] args ) {

        //With arguments, with return value
        Lambda3 lambda3 = (a, b) -> a + b;
        System.out.println(lambda3.test(100,3000));
    }
    interface Lambda3 {
        int test(int a, int b);
    }
}

Implementation result: 3100

Recommended Posts

Introduction to lambda expression
[Java] Introduction to lambda expressions
[Introduction to Java] About lambda expressions
Introduction to Ruby 2
Introduction to SWING
Introduction to web3j
Introduction to Micronaut 1 ~ Introduction ~
[Java] Introduction to Java
Introduction to migration
[Java] Lambda expression
Introduction to java
Introduction to Doma
Java lambda expression
Transform from a normal class to a lambda expression
Introduction to JAR files
Introduction to Ratpack (8)-Session
Introduction to RSpec 1. Test, RSpec
java neutral lambda expression 1
Introduction to bit operation
Introduction to Ratpack (9) --Thymeleaf
Java lambda expression variations
Introduction to Android Layout
Introduction to design patterns (introduction)
How to use Java API with lambda expression
Introduction to Practical Programming
Introduction to javadoc command
Java 8 lambda expression Feature
java lambda expression memo
Introduction to jar command
Introduction to Ratpack (2)-Architecture
Java8 to start now ~ forEach and lambda expression ~
Java lambda expression [memo]
Studying Java 8 (lambda expression)
Introduction to java command
Review java8 ~ Lambda expression ~
Java lambda expression again
Introduction to RSpec 2. RSpec setup
Introduction to Keycloak development
Introduction to javac command
Introduction to Design Patterns (Builder)
[Java] Functional interface / lambda expression
Introduction to RSpec 6. System specifications
Introduction to Android application development
Introduction to RSpec 3. Model specs
Introduction to Ratpack (5) --Json & Registry
Introduction to Metabase ~ Environment Construction ~
Introduction to Ratpack (7) --Guice & Spring
Introduction to Design Patterns (Composite)
Introduction to Micronaut 2 ~ Unit test ~
Introduction to JUnit (study memo)
Java8 stream, lambda expression summary
Introduction to Spring Boot ① ~ DI ~
Introduction to design patterns (Flyweight)
Introduction to Spring Boot ② ~ AOP ~
What is a lambda expression?
Introduction to Apache Beam (2) ~ ParDo ~
[Ruby] Introduction to Ruby Error statement
Introduction to EHRbase 2-REST API
Memoization recursion with lambda expression
Introduction to design patterns Prototype
GitHub Actions Introduction to self-made actions