LoginSignup
5
5

More than 5 years have passed since last update.

JAVA ラムダ式

Last updated at Posted at 2016-01-06

関数をその場で作る

関数型インターフェース(抽象メソッドが1つだけ定義されているインターフェース)の変数に代入する箇所ではラムダ式を渡すことが出来る。

見た目上は、無名内部クラス(匿名クラス)を短く記述できる記法と言える。

■ラムダ式の構文
(型 引数名1, 型 引数名2,…) -> {
処理1;
処理2;
:
return 戻り値;
}

※ラムダ式がJVMによって評価されると、関数の実体が生成され、
その実体を指す参照(関数オブジェクト)に化ける

▪️Lambda.java

import java.util.function.*;

public class Lambda {
    public static void main(String[] args) {
        IntBinaryOperator func = (int a, int b) -> {
            return a - b;
        };
        System.out.println(func.applyAsInt(12, 7));
    }

}

▪️Lambda.java Execution(executed program result)
5

▪️Test85.java

import java.util.function.*;

public class Test85 {
    public static void main(String[] args) {
        IntToDoubleFunction func = (int x) -> {
            return x * x * 3.14;
        };
        System.out.println(func.applyAsDouble(30));

        IntSupplier iii = () -> {
            return 2;
        };
        System.out.println(iii.getAsInt());

        IntPredicate ip = (int i) -> {
            return true;
        };
        System.out.println(ip.test(2));
    }
}

▪️Test85.java Execution(executed program result)
2826.0
2
true

▪️Test88.java

import java.util.function.*;

public class Test88 {
    public static void main(String[] args) {
        IntBinaryOperator func = (int a, int b) -> {
            return a - b;

        };

        System.out.println(func.applyAsInt(10, 4));

    }

}

▪️Test88.java Execution(executed program result)
6

スクリーンショット 2016-01-07 17.15.30.png

E … Element (Javaのコレクション フレームワークで多用されています)
K … Key
N … Number
T … Type
V … Value
S、U、Vなど … 2番、3番、4番目の型

5
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5