11
11

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.

Java8におけるラムダ式のサンプル

Posted at

2014年正式リリース予定のJava8では、「ラムダ式(Lambda expression)」の構文が追加されます。

ここではラムダ式によるソースコードの簡素化を通して、Java8におけるラムダ式の簡単な例を紹介します。

目標

ここに、おなじみの匿名クラスとして実装したComparatorがあります。

Comparator<Integer> c = new Comparator<Integer>() {
    @Override
    public int compare(Integer a, Integer b) {
        return a - b;
    }
};

それを、こう。

Comparator<Integer> c = (a, b) -> a - b;

ステップ1: ラムダ式の導入

元の実装をラムダ式で置き換えると、以下のようになります。

Comparator<Integer> c = (Integer a, Integer b) -> {
    return a - b;
};

1つの文で実装できる場合、上記のブロック部分は式で記述することもできます。
この場合、returnの記述は不要です。

Comparator<Integer> c = (Integer a, Integer b) -> a - b;

ステップ2: 型の省略

型推論により、仮引数の型は省略できます。

Comparator<Integer> c = (a, b) -> a - b;

参考資料

ラムダ式についてはこちらのFAQを参照。
http://www.lambdafaq.org/what-is-a-lambda-expression/

11
11
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
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?