lambda 表达式
Lambda 表达式的基础语法:JAVA8中引入了一个新的操作符 " -> " 改操作符称为箭头操作符或 Lambda 操作符;
- 箭头操作符将Lambda表达式拆分为两部分:
- 左侧: Lambda 表达式的参数列表
- 右侧: Lambda 表达式中所需执行的功能,即Lambda体
语法格式一:无参数,无返回值
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("Hello");
}
};
Runnable r2 = () -> System.out.println("Hello");
r1.run();
r2.run();
语法格式二:有一个参数,无返回值
Consumer<String> tConsumer = (x) -> System.out.println(x);
tConsumer.accept("123");
语法格式三:若有一个参数,小括号可以省略不写
Consumer<String> consumer = x -> System.out.println(x);
consumer.accept("456");
语法格式四:有两个以上的参数,有返回值,并且Lambda 体中有多条语句
Comparator<Integer> tComparator = (x, y) -> {
return Integer.compare(x, y);
};
tComparator.compare(1, 2);
语法格式五:若Lambda体重,只有一条语句,return和大括号都可以省略不写
tComparator = (x, y) -> Integer.compare(x, y);
tComparator.compare(4,3);
语法格式六: Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出数据类型,即"类型推断"
tComparator = (Integer x,Integer y) -> Integer.compare(x,y);
函数式接口
Lambda表达式需要函数式接口的支持。
- 函数式接口:接口中只有一个抽象法的接口,称为函数式接口。
- 可以使用@FunctionalInterface修饰。
- 可以检查是否是函数式接口
场景练习
- 声明函数式接口,接口中声明抽象方法, public String getValue(String str);
- 声明类 TestLambda , 类中编写方法使用接口作为参数,将一个字符串转换成大写,并作为返回值。
- 再讲一个字符串的第二个和第四个 索引位置进行 截取子串
@FunctionalInterface
public interface IStrCaseLambda {
String getValue(String str);
}
public class TestLambda2 {
public static void main(String[] args) {
final String s = strHandler("abcd", (str) -> str.toUpperCase());
final String s2 = strHandler("abcde", (str) -> str.substring(2,5));
System.out.println(s);
System.out.println(s2);
IStrCaseLambda is = (str) -> str.toUpperCase();
String cccddd = is.getValue("cccddd");
System.out.println(cccddd);
}
public static String strHandler(String str, IStrCaseLambda iStrCaseLambda) {
return iStrCaseLambda.getValue(str);
}
}
内置的四大核心函数式接口
- Consumer :消费型接口 void accept(T t);
-有参,无返回值。 - Supplier :供给型接口 T get();
-无参,有返回值 - Function<T,R> :函数型接口 R apply(T t);
-有参数,有返回值 - Predicate :断言型接口 boolean test(T t);
-匹配型,返回满足条件与否的布尔值。

|