几种基础语法
一、Lambda 表达式的基础语法:Java8中引入了一个新的操作符 "->" 该操作符称为箭头操作符或 Lambda 操作符
箭头操作符将 Lambda 表达式拆分成两部分:
左侧:Lambda 表达式的参数列表
右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体,参数就是接口中,抽象方法的参数,如果有多个抽象方法怎么办? 函数式编程中,接口只能有一个抽象方法。
1. 语法格式一:无参数,无返回值
() -> System.out.println("Hello Lambda!");
2. 语法格式二:有一个参数,并且无返回值
(x) -> System.out.println(x)
3. 语法格式三:若只有一个参数,小括号可以省略不写
x -> System.out.println(x)
4. 语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
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);
6. 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
(Integer x, Integer y) -> Integer.compare(x, y);
Lambda 表达式需要“函数式接口”的支持
函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰
可以检查是否是函数式接口
@FunctionalInterface
public interface MyFun {
public Integer getValue(Integer xy);
}
public static Integer getFunValue(Integer num,MyFun fun){
return fun.getValue(num);
}
public static void m2(){
System.out.println(getFunValue(12,x-> {return x + 10;}));
}
四大核心函数式接口
- 消费性接口:
public static void test1(){
consum(10,(x)->System.out.println("消费了: "+x));
}
//Consumer<T> 消费型接口 :
public static void consum(int m, Consumer<Integer> consumer){
consumer.accept(m);
}
- 供给型接口
public static void test2(){
int value = supplier(11,()-> 11*11);
System.out.println(value);
}
//供给型接口
public static int supplier(int n, Supplier<Integer> supplier){
return supplier.get();
}
- 函数型接口
public static void test3(){
function("test",(x)->{return x.length();});
}
//函数型接口
public static Integer function(String str, Function<String,Integer> function){
return function.apply(str);
}
- 断言型接口
public static void test4(){
boolean result = predicate("123qwe",(x)->x.equals("123qwe"));
System.out.println(result);
}
//断言型接口
public static boolean predicate(String str, Predicate<String> predicate){
return predicate.test(str);
}