目录
为什么使用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);
示例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<String> con = (x) -> System.out.println(x);
con.accept("该怎么办呢");
示例3: 语法格式三:若只有一个参数,小括号可以省略不写
Consumer<String> con = x -> System.out.println(x);
con.accept("该怎么办呢");
示例四:语法格式四:有两个以上的参数,有返回值,并且lmabda体中有多条语句
含有输出语句和比较语句
Comparator<Integer> com = (x,y) ->{
System.out.println("函数式接口");
return Integer.compare(x,y);
};
示例5:语法格式五:若lambda体中只有一条语句,return 和大括号都可以省略不写
两数比较
Comparator<Integer> com = (x,y) ->Integer.compare(x,y);
Lambda 表达式需要“函数式接口”的支持
函数式接口:接口中只有一个抽象方法的接口,可以使用注解@FunctionalInterface修饰,可以检查接口是否是函数式接口
@FunctionalInterface
public interface MyPredicate<T>{
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>:对类型为T的对象应用操作,包含方法:void accept(T t)
Supplier<T>:返回类型为T的对象,包含方法T get();
Function<T,R> 对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t)
Predicate<T> 确定类型为T的对象是否满足某约束,并返回boolean值。包含方法 boolean test(T t)
示例1:Consumer<T>接口:对类型为double的对象money打印输出
示例2:Supplier<T>:产生指定个数的整数,并放入集合中
示例3: Function<T,R> 对类型为:String的对象进行截取,并返结果是String类型的对象。
示例4:Predicate<T> :确定类型为String的对象是否满足字符串长度大于3, 将满足条件的字符串放入集合中。