Item 43: Prefer method references to lambdas
43. Use method references rather than lambda expressions
- Basically, method references should be selected because method references can be written more concisely than lambda expressions.
- In some cases, the lambda expression is more concise. This is often the case when using methods in the same class.
//Method reference
service.execute(GoshThisClassNameIsHumongous::action);
//Lambda expression
service.execute(() -> action());
- Many method references are static method references, but there are four other patterns.
- Bound reference (I don't understand ...) is a method reference that identifies the object to receive.
- UnBound references (I don't know why ...) identify the object to receive when applying a function object (** I don't know what it means **). Often used in stream maps and filters.
- Class and array constructors can be as shown in the table below.
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<K,V>::new |
() -> new TreeMap<K,V> |
Array Constructor |
int[]::new |
len -> new int[len] |