Lambda表达式

Lambda表达式支持将代码块作为方法的参数,它允许使用更简洁的代码来创建只有一个抽象方法的接口,亦即是函数式接口(FunctionalInterface)

如果不采用Lambda表达式,我们动态的向接口传入代码就必须使用匿名内部类实例,亦即是下面这个例子

interface Converter{
	Integer convert(String from);
}
public class Test {
	public static void main(String[] args) {
		Converter con3 = new Converter() {
			@Override
			public Integer convert(String from) {
				return Integer.parseInt(from);
			}
		};
		con3.convert("100");
	}
}

Lambda表达式完全可以简化创建匿名内部类对象,如下:


@FunctionalInterface
interface Converter{
	Integer convert(String from);
}
public class Test {
	public static void main(String[] args) {
		Converter con1 = from ->Integer.parseInt(from);
		System.out.println(con1.convert("10"));
		Converter con2 = Integer::valueOf;
		System.out.println(con2.convert("10"));
	}
}

Lambda表达式有三个部分组成:

  • 形参列表,也即是上面代码的from
  • 箭头(->)
  • 代码块,如果代码块只有一条语句,可以省略代码块的花括号,如果只有一条return,可以省略return,他会自动返回值。

下面是更多例子:

import javax.swing.JFrame;

@FunctionalInterface
interface MyTest{
	String test(String a,int b,int c);
}

@FunctionalInterface
interface FrameTest{
	JFrame win(String title);
}

class TestClass{
	int indexOf(String from) {
		return Integer.parseInt(from);
	}
}

public class Test {
	public static void main(String[] args) {

		TestClass tc = new TestClass();
		
		Converter con1 = from ->Integer.parseInt(from);
		System.out.println(con1.convert("10"));
		
		Converter con2 = Integer::valueOf;
		System.out.println(con2.convert("10"));

		MyTest mt  = (a,b,c)->a.substring(b,c);
		MyTest mt2  = String::substring;
		
		System.out.println(mt.test("hello", 1, 2));
		System.out.println(mt2.test("hello", 2, 3));
		
		FrameTest ft = a ->new JFrame(a);
		ft.win("hello").setVisible(true);
		System.out.println(ft.win("hello"));
		FrameTest ft2 = JFrame::new;
		System.out.println(ft2.win("hello"));
		
	}
}

Lambda支持的方法引用和构造器引用

种类 示例 对应lambda表达式
引用类方法 类名::类方法 (a,b,…)->类名.类方法(a,b,…)
引用特定对象的实例方法 特定对象::实例方法 (a,b,…)->特定对象.实例方法(a,b,…)
引用某类对象的实例方法 类名::实例方法 (a,b,…)->a.实例方法(b,…)
引用构造器 类名::new (a,b,…)->new 类名(a,b,…)

下面是各个示例:
1,2类似,就不做区分

@FunctionalInterface
interface Converter{
	Integer convert(String from);
}

Converter con1 = from ->Integer.parseInt(from);
System.out.println(con1.convert("10"));
		
//下面就是类名::类方法形式
Converter con2 = Integer::valueOf;
System.out.println(con2.convert("10"));
@FunctionalInterface
interface MyTest{
	String test(String a,int b,int c);
}

MyTest mt  = (a,b,c)->a.substring(b,c);

//下面就是第三种方法引用,函数式接口中被实现的第一个参数为调用者
//后面的参数全部传给该方法作为参数
MyTest mt2  = String::substring;

4.引用构造器

@FunctionalInterface
interface FrameTest{
	JFrame win(String title);
}


FrameTest ft = a ->new JFrame(a);
System.out.println(ft.win("hello"));


FrameTest ft2 = JFrame::new;
System.out.println(ft2.win("hello"));

下面下一个Lambda比较常用的

new Thread(()-> System.out.println("lambda")).start();	
posted @ 2019-03-31 09:51  clay_ace  阅读(129)  评论(0编辑  收藏  举报