標籤:
JAVA8 的函數引用和 lambda運算式的關係=>函數引用是一種簡化的 lambda運算式,只給出現有的函數,參數和傳回值編譯器推斷去吧.
其實這文法和 lambda運算式正好相反, lambda運算式表示匿名方法,就是沒有函數名,只給出參數和方法體.那麼現有的函數就派上用場了,現有的函數有方法名,給出方法名,參數和方法體都已經有了,由編譯器推斷出.
註:java中的方法不能獨立存在,必須包含在類型中,這就是 lambda運算式 @FunctionalInterface的限制.
Recall that we can think of lambda expressions as methods that don’t have names.
Now, consider this lambda expression:
// In real code this would probably be shorter because of type inference
(MyObject myObj) -> myObj.toString()
This will be autoconverted to an implementation of a @FunctionalInterface that
has a single nondefault method that takes a single MyObject and returns String.
However, this seems like excessive boilerplate, and so Java 8 provides a syntax for
making this easier to read and write:
MyObject::toString
This is a shorthand, known as a method reference, that uses an existing method as a
lambda expression. It can be thought of as using an existing method, but ignoring
the name of the method, so it can be can used as a lambda, and autoconverted in the
usual way.
JAVA8 之 Method References-Java in a Nutshell, 6th