公司建网站需要多少钱网络营销的内容
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; }
}