[Introduction to Java] About lambda expressions


For those who have just started learning programming including the Java language, and those who have already learned it, for review This time I'm writing to learn about ** lambda expressions **.

[Introduction to Java Table of Contents] -Variables and typesType conversion -Variable Scope -String operation -Array operationOperator ・ Conditional branch (in preparation) ・ Repeat processing (in preparation) ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation) -Exception handling ・ About lambda expression ← Now here ・ About Stream API

What is a lambda expression?

The functional interface was implemented by using an anonymous class (anonymous class). The source code was not readable and tended to be redundant.

The ** lambda expression ** solves such problems. It is a syntax introduced from Java8, and the same implementation as using an anonymous class (anonymous class) has become possible in a simple and highly readable state.

** Lambda expression syntax ** (Argument of method to implement)-> {Processing};

Lambda expression example

Let's compare with a simple example how simple and readable it actually became.

First, implementation in an anonymous class (anonymous class).

Anonymous class (anonymous class)

//Self-made functional interface
interface Greet {
  String sayHello(String name);

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

    //Create an instance of an anonymous class that implements the Greet interface
    Greet case1 = new Greet(){

      //Override abstract method sayHello
      public String sayHello(String name) {
        return name + "San, Hello!";


    //Pass the string to the implemented sayHello method
    String tanaka = case1.sayHello("tanaka");
    System.out.println(tanaka); //Mr. tanaka, Hello! Is output


Then implement a similar process with a lambda expression.

Lambda expression

//Self-made functional interface
interface Greet {
  String sayHello(String name);

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

    //Implement Greet interface with lambda expression and instantiate
    Greet case2 = (String name) -> { return name + "San, Hello!"; };

    //Pass the string to the implemented sayHello method
    String suzuki = case2.sayHello("suzuki");
    System.out.println(suzuki); //Mr. suzuki, Hello! Is output

It can be overridden without writing new Greet () and the method name of the abstract method in it. This is because the functional interface has only one abstract method, so ** lambda expressions can determine which method to implement **.

Omitted description of lambda expression

In addition, it is possible to omit it further only in specific cases.

1. Type omission by type inference


Greet case2 = (String name) -> { return name + "San, Hello!"; };


Greet case2 = (name) -> { return name + "San, Hello!"; };

Since the method argument type is determined when the functional interface is declared, it can be omitted to `without specifying the argument type at the time of implementation.

2. Omission of ()


Greet case2 = (String name) -> { return name + "San, Hello!"; };


Greet case2 = name -> { return name + "San, Hello!"; };

If there is only one argument, () can be omitted. However, if there is no argument, there are multiple arguments, or even if there is only one argument, the type cannot be omitted.

3. Omission of {}


Greet case2 = (String name) -> { return name + "San, Hello!"; };


Greet case2 = name -> name + "San, Hello!";

If the process is one sentence, {} can be omitted. Also, if {} is omitted, return can be omitted.

You can write it simply!

Introduction of functional interface

The previous example was using a self-made functional interface, Here are some examples of functional interfaces provided as a java.util.function package.

1.Function<T, R>

Takes an argument of type T and returns a value of type R. The method is R apply (T t).

Function example

Function<Integer, String> funcTest = number -> number + "is";
String resutlt = funcTest.apply(19);
System.out.println(resutlt); //19


Receives an argument of type T. The method is void accept (T t).

Consumer example

Consumer<String> weather = str -> System.out.println("How is the weather today" + str);
weather.accept("It's rain"); // 今日の天気はIt's rain


Receives an argument of type T. The method is boolean test (T t).

Predicate example

Predicate<String> check = str -> 5 < str.length();
boolean result = check.test("Mitarashi dumpling");
System.out.println(result); // true

boolean result2 = check.test("Mame Daifuku");
System.out.println(result2); // false


It does not receive anything as an argument. The method is T get ().

Supplier example

Supplier<String> name = () -> "Ichiro Suzuki";
System.out.println(name.get()); //Ichiro Suzuki


An interface that extends Function. Both the type received as an argument and the type returned are the same. The method is T apply (T t).

Unary Operator example

UnaryOperator<String> breakfast = food -> "After all in the morning" + food;
System.out.println(breakfast.apply("curry")); // 朝はやっぱりcurry

Use lambda expressions in other methods

It is also possible to implement the methods provided around the collection framework using lambda expressions. (Multiple objects can be stored, retrieved, and deleted) This is because it receives a functional interface as a method argument. Here are some of them as well.

1.default boolean removeIf(Predicate<? super E> filter)

This method deletes all collection elements that satisfy the specified processing.

removeIf method

List<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
numbers.removeIf(number -> number % 2 == 0); //Divide by 2 and remove the ones that are 0
System.out.println(numbers); // [1, 3, 5]

2.default void replaceAll(UnaryOperator<E> operator)

A method that performs the specified processing and replaces the elements of the list.

replaceAll method

List<String> names = Arrays.asList("tanaka", "suzuki", "yamada");
names.replaceAll(name -> name.toUpperCase()); //Replace all uppercase
System.out.println(names); // [TANAKA, SUZUKI, YAMADA]

3.default void sort(Comparator<? super E> c)

A method that sorts the list according to the specified order.

sort method

List<Integer> randomNum = Arrays.asList(30, 50, 10, 20, 40);
randomNum.sort((a, b) -> b.compareTo(a)); //Sort in descending order
System.out.println(randomNum); // [50, 40, 30, 20, 10]

randomNum.sort((Integer a, Integer b) -> { return a.compareTo(b); } ); //Sort in ascending order
System.out.println(randomNum); // [10, 20, 30, 40, 50]

4.void forEach(Consumer<? super T> action)

A method that performs the specified action on all elements.

forEach method

List<String> names = Arrays.asList("tanaka", "suzuki", "yamada");

//name+I am trying to output one by one, separated by a half-width space
names.forEach(name -> System.out.print(name + " ")); // tanaka suzuki yamada

At the end

I touched on the syntax of lambda expressions. It is convenient that the source code is shortened and only the implementation part needs to be described.

I will summarize the Stream API in a separate article.

Reference site

java.util.function ** [For beginners] Can't you hear more now? Learn about Java 8 lambda expressions! **

Recommended Posts

[Introduction to Java] About lambda expressions
[Java] Introduction to lambda expressions
About Java lambda expressions
[Introduction to Java] About Stream API
[Java] Introduction to Java
Introduction to java
How to use Java lambda expressions
I tried to summarize Java lambda expressions
Understand Java 8 lambda expressions
Introduction to lambda expression
Explain Java 8 lambda expressions
Introduction to java command
[Introduction to Java] About type conversion (cast, promotion)
[Java] Summary of how to abbreviate lambda expressions
[Java] Introduction to Stream API
[Introduction to rock-paper-scissors games] Java
[Java Silver] Summary of points related to lambda expressions
About C # lambda expressions and Linq
Java lambda expressions learned with Comparator
About Lambda, Stream, LocalDate of Java8
Introduction to Functional Programming (Java, Javascript)
Initial introduction to Mac (Java engineer)
[Java] Introduction
Getting started with Java lambda expressions
The origin of Java lambda expressions
[Introduction to Java] About exception handling (try-catch-finally, checked exception, unchecked exception, throws, throw)
Introduction to java for the first time # 2
Nowadays Java lambda expressions and Stream API
About the procedure for java to work
Introduction to algorithms with java --Search (depth-first search)
[Introduction to Java] How to write a Java program
Output of the book "Introduction to Java"
Introduction to monitoring from Java Touching Prometheus
[Introduction to Java] Variable declarations and types
Easy to trip with Java regular expressions
Introduction to Java Web Apps Performance Troubleshooting
Introduction to algorithms with java --Search (breadth-first search)
Introduction to Ruby 2
About Java interface
[Java] About Java 12 features
[Java] About arrays
Introduction to SWING
About MacinCloud introduction
Something about java
Where about java
About Java features
Introduction to web3j
About Java threads
[Java] About interface
Introduction to Micronaut 1 ~ Introduction ~
About Java class
About Java arrays
Introduction to migration
Hello Java Lambda
[Java] Lambda expression
[Introduction to Java] About array operations (1D array, 2D array declaration, instantiation, initialization and use)
About java inheritance
About interface, java interface
Introduction to Doma
[Introduction to Java] About iterative processing (while, do-while, for, extension for, break, continue)
Java lambda expression