差異處
這裏顯示兩個版本的差異處。
下次修改 | 前次修改 | ||
java:effective_java:lambdas_and_streams:prefer_method_references_to_lambdas [2019/07/18 22:58] tony 建立 |
java:effective_java:lambdas_and_streams:prefer_method_references_to_lambdas [2023/06/25 09:48] (目前版本) |
||
---|---|---|---|
行 2: | 行 2: | ||
====== Effective Java - Prefer method references to lambdas ====== | ====== Effective Java - Prefer method references to lambdas ====== | ||
===== Introduction & My Opinion ===== | ===== Introduction & My Opinion ===== | ||
+ | 這個item回歸Lambda的目的之一: 讓程式更清晰簡潔。以書中範例來說,它使用了Map的merge功能: | ||
+ | <code java> | ||
+ | map.merge(key, 1, (count, incr) -> count + incr); | ||
+ | </code> | ||
+ | 以這段程式碼來說,假如key有重複,它會將old value與第二個參數的new value相加。假如改用method reference的寫法,會更容易表達意圖: | ||
+ | <code java> | ||
+ | map.merge(key, 1, Integer::sum); | ||
+ | </code> | ||
+ | 但使用method reference也有可能不會達到更好效果,這個可以自行判斷。另外書中整理了以下五種method reference的方式:\\ | ||
+ | \\ | ||
+ | {{:java:effective_java:lambdas_and_streams:effective_java_method_ref.png|}}\\ | ||
+ | \\ | ||
+ | **Note.** Bound指的是有參數的method reference,Unbound是無參數的。\\ | ||
+ | \\ | ||
+ | 其它範例可以參考[[https://www.baeldung.com/java-method-references|link]]。 | ||
===== Note ===== | ===== Note ===== | ||
Effective Java第三版Item 43。 | Effective Java第三版Item 43。 | ||
===== Reference ===== | ===== Reference ===== | ||
* Effective Java, 3/e | * Effective Java, 3/e | ||
+ | * [[https://www.baeldung.com/java-method-references|Method References in Java]] | ||
===== ===== | ===== ===== | ||
---- | ---- | ||
\\ | \\ | ||
~~DISQUS~~ | ~~DISQUS~~ | ||
+ |