LoginSignup
1
0

More than 5 years have passed since last update.

Item 43: Prefer method references to lambdas

Posted at

43.ラムダ式よりメソッド参照を使うべし

  • 基本的にラムダ式よりメソッド参照の方が簡潔に書けるため、メソッド参照を選択するべき。
  • ラムダ式の方が簡潔に書ける場合もある。よくあるのは、同クラスにあるメソッドを用いる場合。
// メソッド参照
service.execute(GoshThisClassNameIsHumongous::action);
// ラムダ式
service.execute(() -> action());
  • 多くのメソッド参照はstaticメソッドの参照であるが、他にも4つのパターンがある。
    • Bound 参照(訳が分からない。。)はメソッド参照において、受け取るオブジェクトが特定される。
    • UnBound 参照(訳が分からない。。)は関数オブジェクトを適用するときに、受け取るオブジェクトが特定される(意味がよくわからない)。streamのmapやfilterでよく使われる。
    • クラス、配列のコンストラクタについては以下の表のようにできる。
Method Ref Type Example Lambda Equivalent
Static Integer::parseInt str -> Integer.parseInt(str)
Bound Instant.now()::isAfter Instant then = Instant.now(); t -> then.isAfter(t)
Unbound String::toLowerCase str -> str.toLowerCase()
Class Constructor TreeMap::new () -> new TreeMap
Array Constructor int[]::new len -> new int[len]
1
0
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
0