Java 8 特性-Lambda 表达式

Lambda 表达式

Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性。

Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。

使用 Lambda 表达式可以使代码变的更加简洁紧凑。

示例

首先定义三个接口,每个接口都包含一个方法

public interface MathOperation {
	int operation(int a, int b);
}

public interface PlaceOperation {
	void operation(String str);
}
  
public interface MessageOperation {
	String operation(String str);
}

测试类

public static void main(String[] args) {
	MathOperation mathOperation = (a, b) -> a + b;
	int operation = mathOperation.operation(1, 4);
	System.out.println(operation);

	PlaceOperation placeOperation = str -> System.out.println(str);
	placeOperation.operation("我是谁?");

	MessageOperation messageOperation = (str) -> {
		System.out.println("hello" + str);
		return "写完了";
	};
	String operation2 = messageOperation.operation("java");
	System.out.println(operation2);
}

运行结果

TIPS

lambda 表达式只能引用标记了 final 的外层局部变量,这就是说不能在 lambda 内部修改定义在域外的局部变量,否则会编译错误。

我们也可以直接在 lambda 表达式中访问外层的局部变量:lambda 表达式的局部变量可以不用声明为 final,但是必须不可被后面的代码修改(即隐性的具有 final 的语义)

扫描二维码关注公众号,回复: 9057967 查看本文章
int num = 1;  
Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num));
s.convert(2);
num = 5;  
//报错信息:Local variable num defined in an enclosing scope must be final or effectively 
// final

在 Lambda 表达式当中不允许声明一个与局部变量同名的参数或者局部变量。

String first = "";  
Comparator<String> comparator = (first, second) -> Integer.compare(first.length(), second.length());  
//编译会出错 

 

自定义函数式接口

在接口上添加注解@FunctionalInterface,这样做可以检查它是否是一个函数式接口,同时javac也会包含一条声明,说明这个接口是函数接口。

@FunctionalInterface
public interface MyInter {
	void getOut();
}

//接口中使用泛型
@FunctionalInterface
public interface MyInter<T> {

	T getOut(T t);
}

四大内置核心函数式接口

在开发中我们可以使用java8提供的自定义函数接口,这样我们就不需要自己创建接口使用lamda表达式

/*
 * Consumer<T> : 消费型接口void accept(T t);
 * Supplier<T> : 供给型接口T get(); 
 * Function<T, R> : 函数型接口R apply(T t);
 * Predicate<T> : 断言型接口boolean test(T t);
 */
public class TestLambda3 {
	//Predicate<T> 断言型接口:
	@Test
	public void test4(){
		List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
		List<String> strList = filterStr(list, (s) -> s.length() > 3);
		for (String str : strList) {
			System.out.println(str);
		}
	}
	//需求:将满足条件的字符串,放入集合中
	public List<String> filterStr(List<String> list, Predicate<String> pre){
		List<String> strList = new ArrayList<>();
		for (String str : list) {
			if(pre.test(str)){
				strList.add(str);
			}
		}	
		return strList;
	}

	//Function<T, R> 函数型接口:
	@Test
	public void test3(){
		String newStr = strHandler("\t\t\t 我大尚硅谷威武   ", (str) -> str.trim());
		System.out.println(newStr);
		String subStr = strHandler("我大尚硅谷威武", (str) -> str.substring(2, 5));
		System.out.println(subStr);
	}
	//需求:用于处理字符串
	public String strHandler(String str, Function<String, String> fun){
		return fun.apply(str);
	}

	//Supplier<T> 供给型接口 :
	@Test
	public void test2(){
		List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));
		for (Integer num : numList) {
			System.out.println(num);
		}
	}
	//需求:产生指定个数的整数,并放入集合中
	public List<Integer> getNumList(int num, Supplier<Integer> sup){
		List<Integer> list = new ArrayList<>();
		for (int i = 0; i < num; i++) {
			Integer n = sup.get();
			list.add(n);
		}
		return list;
	}

	//Consumer<T> 消费型接口 :
	@Test
	public void test1(){
		happy(10000, (m) -> System.out.println("你们刚哥喜欢大宝剑,每次消费:" + m + "元"));
	} 
	public void happy(double money, Consumer<Double> con){
		con.accept(money);
	}
}

其他类型的接口

发布了188 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_36154832/article/details/103575601