package com.zwq;
import org.junit.Test;
import java.util.Comparator;
import java.util.function.Consumer;
/**
* @author zhangwq
*
* Lambda语法格式
* 1、无参数,无返回值 ()->System.out.println("hello world!");
* 2、有一个参数无返回值 (x)->System.out.println(x);
* 3、有一个参数,小括号可以不写
* 4、有两个及以上参数,有返回值,lambda体有多条语句,需要{}需要return
* 5、lambda体只有一条语句,return和{}可以省略
* 6、lambda表达式数据类型可以省略,“类型推断”
* 7、函数式接口支持,只有一个抽象方法
*/
public class LambdaLearn {
@Test
public void test(){
//1
Runnable runnable = ()-> System.out.println("hello");
runnable.run();
//2
Consumer<Integer> con = (x)-> System.out.println("接收到值:"+x);
con.accept(1);
//3
Consumer<Integer> consumer = x-> System.out.println("接收到值:"+x);
consumer.accept(2);
//4
Comparator<Integer> comparator = (Integer x,Integer y)->{
System.out.println("多条语句");
return Integer.compare(x,y);
};
System.out.println(comparator.compare(1,2));
//5
Comparator<Integer> com = (Integer x,Integer y)-> Integer.compare(x,y);
System.out.println(com.compare(2,1));
//6
Comparator<Integer> comNoType = (x,y)-> Integer.compare(x,y);
System.out.println(comNoType.compare(2,2));
//7
String wlfsb = oprator("man",(x) -> "I am a "+x);
System.out.println(wlfsb);
}
public String oprator(String str,MyFunction myFunction){
return myFunction.doMyOperation(str);
}
}
Lambda语法格式
猜你喜欢
转载自blog.csdn.net/zwq_zwq_zwq/article/details/81750827
今日推荐
周排行