网站开发浏览器兼容,门户网站建设的成果,域名查询中国万网,租国外服务器一个月多少钱Lambada表达式全面详解 文章目录 Lambada表达式全面详解前言入门类名引用静态方法对像名引用方法构造器引用 前言
Lambda 表达式是 JDK8 的一个新特性#xff0c;可以取代大部分的匿名内部类#xff0c;写出更优雅的 Java 代码#xff0c;尤其在集合的遍历和其他集合操作中…Lambada表达式全面详解 文章目录 Lambada表达式全面详解前言入门类名引用静态方法对像名引用方法构造器引用 前言
Lambda 表达式是 JDK8 的一个新特性可以取代大部分的匿名内部类写出更优雅的 Java 代码尤其在集合的遍历和其他集合操作中可以极大地优化代码结构。JDK 也提供了大量的内置函数式接口供我们使用使得 Lambda 表达式的运用更加方便、高效。 虽然使用 Lambda 表达式可以对某些接口进行简单的实现但并不是所有的接口都可以使用 Lambda 表达式来实现。Lambda 只能针对只有一个抽象方法的接口实现。
函数式接口 接口有且仅有一个抽象方法才能使用lambad表达式。 函数式接口是指有且仅有一个抽象方法的接口。 Java8引入了注解FunctionalInterface修饰函数式接口的要求接口中的抽象方法只有一个。
方法的引用 Lambda主体只有一条语句时程序可以省略主体大括号还可以通过英文“ :: ”来引用方法和构造器。两种方式:
种类Lambda表达式对应引用示例类名引用普通方法(x,y,…)-对象名x.类普通方法(x,y,…)类名 :: 类普通方法类名引用静态方法(x,y,…)-类名.类静态方法(x,y,…)类名 :: 类静态方法名对像名引用方法(x,y,…)-对象名.实例方法(x,y,…)对象名 :: 实例方法名构造器引用(x,y,…)-new 类名(x,y,…)类名 :: new
入门
代码示例
public class Test {//函数式接口用于声明方法 interface Person {void say();}interface Person2 {int custom(int i, int j);}//客户端调用接口方法可以自定义传入参数 public static void test(Person person) {//... person.say();}public static void test2(Person2 person2) {int i 10;int j 5;//... System.out.println(person2.custom(i, j));}//测试public static void main(String[] args) {//匿名内部类 test(new Person() {Overridepublic void say() {System.out.println(*********);}});//lambada表达式提供方法实现方式 test(() - {System.out.println(**************);});test2((x, y) - x y);test2((x, y) - x - y);}
}lambada表达式完全可以看作是简化匿名内部类的写法因此学习lambada可以以匿名内部类的去理解。
学习Lambada只是学习表达式的写法并没有新技术可言。
类名引用静态方法
public class Test3 {private static void printAbs(int num, Calcable calcable) {System.out.println(calcable.calc(num));}public static void main(String[] args) {//lambda表达式 printAbs(-10, num - Math.abs(num));//方法引用 printAbs(-10, Math::abs);}
}FunctionalInterface
interface Calcable {int calc ( int num);
}class Math {public static int abs(int num) {if (num 0) {return -num;} else {return num;}}
}
对像名引用方法
public class Test3 {private static void printAbs(int num, Calcable calcable) {System.out.println(calcable.calc(num));}public static void main(String[] args) {Math math new Math();//lambda表达式 printAbs(-10, num - math.abs(num));//方法引用 printAbs(-10, math::abs);}
}FunctionalInterface
interface Calcable {int calc(int num);
}class Math {public int abs(int num) {if (num 0) {return -num;} else {return num;}}
}构造器引用
public class Test3 { private static void printName(String name, PersonBuild build){ System.out.println(build.buildPerson(name).getName()); } public static void main(String[] args) { //lambda表达式 printName(junjie,name - new Person(name)); //方法引用 printName(junjie,Person :: new); }
}
FunctionalInterface
interface PersonBuild{ Person buildPerson(String name);
}
class Person{ String name; public Person(String name) { this.name name; } public String getName() { return name;} public void setName(String name) { this.name name; }
}