1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ラムダ式入門

Posted at

何でラムダ式を使うのか?

大規模な開発に使われるJavaでは、なるべくコードの量を減らし読みやすいことを求められています。そのような時役にたつのがJava8で使われている「ラムダ式」です。
ラムダ式の特徴としては、メソッドを変数のように扱えることです。

書き方:

[インタフェース宣言]= (引数->{実行ブロック}

さっそくソースコードから確認してみましょう。
まずは伝統的な表現式:


public class LambdaTest {

    public static void main(String[] args) {
        // 伝統的な表現
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("threading" + Thread.currentThread().getId());
            }
        }).start();
    }
}

次は、Lambda式の表現です。


public class LambdaTest {

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

Java関数型インタフェース

Javaの関数型インタフェースは伝統的なインタフェースとほとんど同じですが、唯一の特徴は関数インタフェースが「定義されている抽象メソッドが1つだけあるインターフェース」であることです。staticメソッドやデフォルトメソッドは含まれていても構わないです。(java.lang.FunctionalInterfaceアノテーションを付けるのが良いでしょう)。

Java関数インタフェースについての詳細紹介を参考ください。
https://qiita.com/Jenny1025/items/470e304ff77c44874fc8

例:

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

Lambda式のメリット

JavaのLambda式のメリットは、匿名クラスを用いる関数型インタフェースの記述を簡潔になることが実現できます。
*匿名クラス:一度だけ使わないようなクラス

匿名クラス:

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

        // 関数型インタフェース
        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"));
        }
    }

では、Lambda式でどう表現するか?

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"));
        }
    }

具体的にラムダ式の書き方の説明

1)宣言:ラムダ式のインタフェースの型
2)引数:()中に記入する。インタフェースの引数の数及び順番と同じ
3)表現式:->
4)実行ブロック:{}中に実装する

では、具体的な例から説明に行きましょう。

引数なし、戻り値なし

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

        // 引数なし、戻り値なし
        Lambda1 lambda1 = () -> System.out.println("Hello world");
        lambda1.test();
    }
    interface Lambda1 {
        void test();
    }
}

実装結果Hello world

引数あり、戻り値なし

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

        // 引数あり、戻り値なし
        Lambda2 lambda2 = (n, a) -> System.out.println(n + " is " + a + " years old");
        lambda2.test("Sally",18);
    }
    interface Lambda2 {
        void test(String name, Integer age);
    }
}

実装結果Sally is 18 years old

引数あり、戻り値あり

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

        // 引数あり、戻り値あり
        Lambda3 lambda3 = (a, b) -> a + b;
        System.out.println(lambda3.test(100,3000));
    }
    interface Lambda3 {
        int test(int a, int b);
    }
}

実装結果3100
1
4
0

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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?