lambda表达式

仅作备忘,要学习还是看给的链接吧
[size=x-large][color=blue]1、C++[/color][/size]
中文介绍:[url]http://www.cnblogs.com/hujian/archive/2012/02/14/2350306.html[/url]
英文介绍:[url]http://www.cprogramming.com/c++11/c++11-lambda-closures.html[/url]
和函数对象的比较(认为函数对象便于日后的维护):[url]http://msdn.microsoft.com/zh-cn/library/dd293608.aspx[/url]

基本用法:
[要引入到函数中的已经存在的变量] (函数的参数) mutable或exception声明 ->返回值类型 {函数体}

其中 (函数的参数) mutable或exception声明 ->返回值类型 均可省略;
例如以下几句完全等效:

[]()->int {return 1;}
[]{return 1;}


[size=x-large][color=blue]2、Java[/color][/size]
jdk8中引入的,有以下形式,参见:[url]http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html[/url]
[quote](int x, int y) -> x + y

() -> 42

(String s) -> { System.out.println(s); }[/quote]

测试代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

interface Inter {
void method();
//void method2();//如果有两个虚方法,会报错:The target type of this expression must be a functional interface
}

/**
* 学校lambda表达式. {@link http
* ://www.oracle.com/webfolder/technetwork/tutorials/obe/
* java/Lambda-QuickStart/index.html}
*
* @author LC
*
*/
public class LabmdaTest {
public static String _FUNC_() {//http://www.cnblogs.com/likwo/archive/2012/06/16/2551672.html
StackTraceElement traceElement = ((new Exception()).getStackTrace())[1];
return traceElement.getMethodName();
}

/**
* 测试labmda表达式用于初始化 interface
*/
static void testLambdaInit() {
System.out.println(_FUNC_()+" ----------------");
/ 方法1:labmda表达式
Inter t = () -> {
System.out.println("In a lambda method.");
};

t.method();

System.out.println();

/ 方法2:匿名类
Inter tt = new Inter() {

@Override
public void method() {
System.out.println("In anonymous class '"
+ this.getClass().getName() + "'");

}
};
tt.method();
}

/**
* 测试lambda表达式作为参数
*/
static void testLambdaAsParam() {
System.out.println(_FUNC_()+" ----------------");
List<Double> l = new ArrayList<Double>();
for (int i = 0; i < 6; i++) {
l.add(new Double(Math.round(Math.random() * 100) / 10));
}
System.out.println("排序前" + Arrays.toString(l.toArray(new Double[0])));
l.sort((d1, d2) -> d1.compareTo(d2));//这里需要两个参数,对于单参数的函数,参数列表的括号也可以省略
//或者:l.sort((Double d1,Double d2)->d1.compareTo(d2));
System.out.println("排序后" + Arrays.toString(l.toArray(new Double[0])));
}

public static void main(String[] args) {
testLambdaInit();
System.out.println();
testLambdaAsParam();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值