If you use Java 8, then you can:
Replace Lambda expressions with method references
Lambda expressions can be replaced with method references. Method reference has following form:
ClassName::methodName
so if you use one letter names for classes it's shorter then lambda. Here are the rules
lambda form | reference method form
-------------------------------------------------------------------------------------------------
p -> ClassName.methodName(p) | ClassName::methodName
p -> new ClassName(p) | ClassName::new
p -> p.methodName() | ClassName::methodName // where ClassName is class of object p
(p, q) -> p.methodName(q) | ClassName::methodName // where ClassName is class of object p
Examples (respectivly):
lambda | reference method
-------------------------------------------------------------------------------------------------
p -> System.out.println(p) | System.out::println
p -> new HashSet<>(p) | HashSet::new
p -> p.getName() | Beer::getName
(p, q) -> p.compareTo(q) | String::compareTo
So, if ClassName is "C", then we have following length diffs:
lambda form | reference method form | length diff
-----------------------------------------------------------------------
p->C.methodName(p) | C::methodName | 5 bytes
p->new C(p) | C::new | 5 bytes
p->p.methodName() | C::methodName | 4 bytes
(p,q)->p.methodName(q) | C::methodName | 9 bytes
Simplify lambda expressions
And here are some rules of simplifying lambda expressions.
General form of lambda expression is
(parameters) -> { statements;} // (String a, String b) -> {return a.compareTo(b);}
When there is only one expresion, it can be simplified as follows (return
should me ommitted):
(parameters) -> expression // (String a, String b) -> a.compareTo(b)
When type declaration can be ommited, it can be simplified as follows:
(parameters) -> expression // (a, b) -> a.compareTo(b)
When there is only one parameter and there is no need to declare type, it can be simplified as follows:
parameter -> expression // (String s) -> System.out.printout(s)
// to
// s -> System.out.println(s)
package
can be skipped. \$\endgroup\$