目录
为什么使用Lambda
Lambda基础格式语法
Lambda 表达式需要“函数式接口”的支持
Java内置四大核心函数式接口
为什么使用Lambda
Lambda是一个匿名函数,我们可以把Lambda表达式理解为一段可以可以传递的代码(将代码像数据一样传递)。可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,是java语言表达能力得到提升。
Lambda基础格式语法
语法格式一:无参数,无返回值
()->需要实现的功能,例如:Runnable r1 = ()-> System.out.println("hello");
语法格式二:有一个参数,并且无返回值
(x)->需要实现的功能,例如: (x) -> System.out.println(x);
语法格式三:若只有一个参数,小括号可以省略不写
x->需要实现的功能,例如: x -> System.out.println(x);
语法格式四:有两个以上的参数,有返回值,并且lmabda体中有多条语句
例如: (x,y) ->{
System.out.println("函数式接口");
return Integer.compare(x,y);
};
语法格式五:若lambda体中只有一条语句,return 和大括号都可以省略不写
例如:(x,y) ->Integer.compare(x,y);
语法格式一:无参数,无返回值
()->需要实现的功能,例如:Runnable r1 = ()-> System.out.println("hello");
语法格式二:有一个参数,并且无返回值
(x)->需要实现的功能,例如: (x) -> System.out.println(x);
语法格式三:若只有一个参数,小括号可以省略不写
x->需要实现的功能,例如: x -> System.out.println(x);
语法格式四:有两个以上的参数,有返回值,并且lmabda体中有多条语句
例如: (x,y) ->{
System.out.println("函数式接口");
return Integer.compare(x,y);
};
语法格式五:若lambda体中只有一条语句,return 和大括号都可以省略不写
例如:(x,y) ->Integer.compare(x,y);
示例1:语法格式一:无参数,无返回值
使用Runnable接口输出一个语句
public static void main(String[] args) {
//不使用Lamabda
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("hello");
}
};
r.run();
//Lamabda表达式
System.out.println("------------");
Runnable r1 = ()-> System.out.println("hello");
r1.run();
示例2:语法格式二:有一个参数,并且无返回值
对参数进行输出操作
//Consumer定义一个参数,对其进行处理,处理的方式可以是任意操作.accept()对给定的参数执行定义的操作
Consumer con = (x) -> System.out.println(x);
con.accept("该怎么办呢");
示例3: 语法格式三:若只有一个参数,小括号可以省略不写
Consumercon = x -> System.out.println(x); con.accept("该怎么办呢");
示例四:语法格式四:有两个以上的参数,有返回值,并且lmabda体中有多条语句
含有输出语句和比较语句
Comparatorcom = (x,y) ->{ System.out.println("函数式接口"); return Integer.compare(x,y); };
示例5:语法格式五:若lambda体中只有一条语句,return 和大括号都可以省略不写
两数比较
Comparatorcom = (x,y) ->Integer.compare(x,y);
Lambda 表达式需要“函数式接口”的支持
函数式接口:接口中只有一个抽象方法的接口,可以使用注解@FunctionalInterface修饰,可以检查接口是否是函数式接口
@FunctionalInterface public interface MyPredicate{ public boolean test(T t);
示例:对一个数进行运算
@FunctionalInterface
public interface MyFunction {
public Integer getValue(Integer num);
}
public class YunSuan {
public static void main(String[] args) {
Integer num = operation(100,(x)->x*x);
Integer num1 = operation(100,x->x+200);
System.out.println(num);
System.out.println(num1);
}
public static Integer operation(Integer num, MyFunction mf){
return mf.getValue(num);
}
}
Java内置四大核心函数式接口
Consumer:对类型为T的对象应用操作,包含方法:void accept(T t)
Supplier:返回类型为T的对象,包含方法T get();
Function 对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t)
Predicate 确定类型为T的对象是否满足某约束,并返回boolean值。包含方法 boolean test(T t)
Consumer
Supplier
Function
Predicate
示例1:Consumer
示例2:Supplier
示例3: Function
示例4:Predicate
暑期编程PK赛 得CSDN机械键盘等精美礼品!



