Lambda [email protected] Java™ Tutorials
https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Java 8裡面正式推出了Lambda表達式。Lambda出現的背景,
One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. In these cases, you're usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data.
聚合操作
The operations filter, map, and forEach are aggregate operations. Aggregate operations process elements from a stream, not directly from a collection (which is the reason why the first method invoked in this example is stream).
流
A stream is a sequence of elements. Unlike a collection, it is not a data structure that stores elements. Instead, a stream carries values from a source, such as collection, through a pipeline.
通道
A pipeline is a sequence of stream operations, which in this example is filter- map-forEach.
一個例子,連起來使用,效率非常好,和腳本語言一緻了。
In addition, aggregate operations typically accept lambda expressions as parameters, enabling you to customize how they behave.
roster
.stream()
.filter(
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25)
.map(p -> p.getEmailAddress())
.forEach(email -> System.out.println(email));
lambda表達式文法
A comma-separated list of formal parameters enclosed in parentheses.
The arrow token
A body, which consists of a single expression or a statement block.
Groovy closure
http://groovy.codehaus.org/Closures
定義
A Groovy Closure is like a "code block" or a method pointer. It is a piece of code that is defined and then executed at a later point. It has some special properties like implicit variables, support for currying and support for free variables
文法
A closure definition follows this syntax: { [closureArguments->] statements }
樣例
def list = ['a','b','c','d']
def newList = []
def clos = { it.toUpperCase() }
list.collect( newList, clos )
assert newList == ["A", "B", "C", "D"]
JavaScript closure
http://jibbering.com/faq/notes/closures/
http://www.javascriptkit.com/javatutors/closures.shtml
定義
A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
a closure is the local variables for a function - kept alive after the function has returned, or
a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)