`

lambda表达式

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

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

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


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

() -> 42

(String s) -> { System.out.println(s); }


测试代码:
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();
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics